A Python IRC bot with dynamically loadable modules

Overview

pybot

This is a modular, plugin-based IRC bot written in Python. Plugins can bedynamically loaded and unloaded at runtime. A design goal is the abillity to develop plugins without being able to crash the bot.

Plugins have a simple, easy to pick up API. All events, commands, and triggers use a simple decorator convention.

Clone with: git clone --recursive https://github.com/jkent/pybot.git

Dependencies

Pybot is designed and tested to run under Python 3. Python 2 is no longer supported. Dependencies are listed in requirements.txt.

Configuring

You need to copy config.yaml.example to config.yaml and edit it to your liking.

The below examples in the Plugins section assume directed_triggers is False. Directed triggers start with the bot's name, followed by a colon or comma, and finally the command and any arguments. The other option, classic triggers, take a ! followed by the command and any arguments. The default option is to use directed triggers, so multiple bots can peacefully coexist.

  • config.yaml:

    my_network:
      host: localhost
      port: 6667
      ssl: false
    
      plugins:
        base:
          connect_password: null
          nickname: pybot
          username: pybot
          realname: Python IRC bot - http://git.io/M1XRlw
          nickserv_password: null
          channels:
              - '#dev'
    

Running

Pybot can be run as either a package or using its pybot.py script. It also comes with a shell script, run.sh that will setup a python virtual environment and dependencies for you.

Plugins

anyurl

This plugin will fetch and reply with the og:title or title of a HTML document.

  • Configuration:

    anyurl:
      blacklist:
        - '^https://www.google.com/.*$'
    

base

This plugin handles some of the core behaviors of the bot, such as setting the nick, joining channels, and auto-reconnect. Its required, please don't unload it unless you know what you're doing.

  • Configuration:

    base:
      nickname: pybot
      channels:
        - #dev
        - #UnderGND
    

choose

A fun yet frustrating plugin that gives random responses.

  • Usage:

    should I|<nick> <question>?
    !choose a or b, c.
    

config

This plugin allows configuration reloading. Usage is limited to level 1000.

  • Usage:

    !config reload
    

debug

This plugin prints all IRC traffic and module events while loaded.

  • Usage:

    !raw <message>
    !eval <code>
    

Raw lets you send a raw IRC message, and requires permission level 900 and up. Eval is a dangerous feature that allows arbitrary execution of python code, and usage requires permission level 1000 and up.

github

This plugin will show information about GitHub users and repos when a url is linked within a channel. jrspruitt was the original author, rewritten by jkent.

  • Usage:

    <url>
    

math

The math plugin is a nifty calculator that has support for functions and variables. Its state is saved in a database as workbooks which can be switched out as needed.

  • Usage:

    !math [expr]
    !math var=[expr]
    !math func([var[, ...]])=[expr]
    !math workbook [name]
    !math varlist
    !math funclist
    !math describe <funcname> [description]
    

message

An offline/delayed message facility.

  • Usage:

    !message send <nick> <message> [as dm] [in timespec]
    !message ack
    !message del <num>
    !message list [nick]
    !message block <nick>
    !message unblock <nick>
    !message opt <in | out>
    

perms

Manage bot permissions. Usage is limited to level 1000.

  • Config:

    perms:
      superuser: [email protected]
    
  • Usage:

    !perms list
    !perms allow [-]<mask> [<plugin>=<n>]
    !perms deny [-]<mask> [<plugin>=<n>]
    

Where plugin is the name of a plugin and n is the level to set. Plugin can be the special constant ANY.

plugin

Load, unload, reload plugins at runtime. Usage is limited to level 1000.

  • Usage:

    !plugin load <name>
    !plugin reload [!]<name>
    !plugin unload [!]<name>
    !plugin list
    

For reload and unload, the "bang" means force. Use with caution.

song

Choose a random song from a song database.

  • Usage:

    !song
    !song add <artist> - <title>
    !song delete
    !song fix artist <artist>
    !song fix title <title>
    !song last
    !song load <data-file>
    !song search <query>
    !song stats
    !song who
    !song [youtube|yt] <youtube-url>
    !song [youtube|yt] delete
    

topic

Allow users to set the topic with a minimum age.

  • Configuration:

    topic:
      min_age: 24h
      min_level: 100
      bypass_level: 900
    
  • Usage:

    !topic apply
    !topic set <topic>
    

If permissions or min_age not met, apply can be used to override and apply the last proposed topic by anyone with bypass_level or higher.

twitter

Parse URLs, get latest user tweet, and search keywords on Twitter. Configuration requires Twitter account and application setup:

  • Configuration:

    twitter:
    apikey: <api key>
    secret: <api secret>
    auth_token: <auth token>
    auth_secret: <auth secret>
    
  • Usage:

    <url>
    !twitter user <@user_id>
    !twitter search <keyword>
    

For Developers

Plugins

Here's a simple "Hello world" style plugin:

from pybot.plugin import *

class Plugin(BasePlugin):
    @hook
    def hello_trigger(self, msg, args, argstr):
        msg.reply('Hello %s!' % (argstr,))

You would call the trigger on IRC via either:

!hello world

or if directed (conversational) style triggers are enabled:

pybot, hello world

To which the bot would reply:

<pybot> Hello world!

Hooks

There are five types of hooks:

  • event
  • command
  • trigger
  • timestamp
  • url

All except for timestamp hooks can be used via the @hook decorator. @hook is a smart decorator that uses the naming convention of your method to determine the name and type of the hook. Alternatively, it can be called as @hook(names) and @hook(type, names).

Timestamp hooks can be created 3 different ways: one-shot timeouts, one-shot timers, and repeating intervals. They are discussed in more detail with the Bot class.

Bot class

Anything that you may need to access should be accessable from the bot class. Plugins get a reference to the bot instance they are running on (self.bot).

var description
channels A dict with keys being channels, value is a dict with keys 'joined' and 'nicks'
core The core instance the bot is running under
hooks An instance of the HookManager class
nick A string identifying the bot's current nickname
plugins An instance of the PluginManager class
allow_rules Allow rules for the permission system
deny_rules Deny rules for the permission system
method description
set_interval(fn, seconds[, owner]) Install timestamp hook, calls fn every seconds
set_timeout(fn, seconds[, owner]) Install timestamp hook, calls fn after seconds
set_timer(fn, timestamp[, owner]) Install timestamp hook, calls fn at timestamp
join(channels[, keys]) Convenience method for JOIN
notice(target, text) Convenience method for NOTICE
part(channels[, message]) Convenience method for PART
privmsg(target, text) Convenience method for PRIVMSG

Hook class

method description
bind(fn[, owner]) Binds a hook in preparation to install

EventHook class

CommandHook class

TriggerHook class

TimestampHook class

UrlHook class

HookManager class (the hook manager)

method description
install(hook) Install a bound hook
uninstall(hook) Uninstall hook
call(hooks, *args) Call hooks using as many args as possible
find(model) Search for hooks by model hook instance
modify(hook) Context manager for modifying installed hooks
Comments
  • Bump urllib3 from 1.25.3 to 1.25.8

    Bump urllib3 from 1.25.3 to 1.25.8

    Bumps urllib3 from 1.25.3 to 1.25.8.

    Release notes

    Sourced from urllib3's releases.

    1.25.8

    Release: 1.25.8

    1.25.7

    No release notes provided.

    1.25.6

    Release: 1.25.6

    1.25.5

    Release: 1.25.5

    1.25.4

    Release: 1.25.4

    Changelog

    Sourced from urllib3's changelog.

    1.25.8 (2020-01-20)

    • Drop support for EOL Python 3.4 (Pull #1774)

    • Optimize _encode_invalid_chars (Pull #1787)

    1.25.7 (2019-11-11)

    • Preserve chunked parameter on retries (Pull #1715, Pull #1734)

    • Allow unset SERVER_SOFTWARE in App Engine (Pull #1704, Issue #1470)

    • Fix issue where URL fragment was sent within the request target. (Pull #1732)

    • Fix issue where an empty query section in a URL would fail to parse. (Pull #1732)

    • Remove TLS 1.3 support in SecureTransport due to Apple removing support (Pull #1703)

    1.25.6 (2019-09-24)

    • Fix issue where tilde (~) characters were incorrectly percent-encoded in the path. (Pull #1692)

    1.25.5 (2019-09-19)

    • Add mitigation for BPO-37428 affecting Python <3.7.4 and OpenSSL 1.1.1+ which caused certificate verification to be enabled when using cert_reqs=CERT_NONE. (Issue #1682)

    1.25.4 (2019-09-19)

    • Propagate Retry-After header settings to subsequent retries. (Pull #1607)

    • Fix edge case where Retry-After header was still respected even when explicitly opted out of. (Pull #1607)

    • Remove dependency on rfc3986 for URL parsing.

    • Fix issue where URLs containing invalid characters within Url.auth would raise an exception instead of percent-encoding those characters.

    ... (truncated)

    Commits
    • 2a57bc5 Release 1.25.8 (#1788)
    • a2697e7 Optimize _encode_invalid_chars (#1787)
    • d2a5a59 Move IPv6 test skips in server fixtures
    • d44f0e5 Factorize test certificates serialization
    • 84abc7f Generate IPV6 certificates using trustme
    • 6a15b18 Run IPv6 Tornado server from fixture
    • 4903840 Use trustme to generate IP_SAN cert
    • 9971e27 Empty responses should have no lines.
    • 62ef68e Use trustme to generate NO_SAN certs
    • fd2666e Use fixture to configure NO_SAN test certs
    • Additional commits viewable in compare view

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependencies 
    opened by dependabot[bot] 0
  • Anyurl requests timeout and user-agent config.ini option.

    Anyurl requests timeout and user-agent config.ini option.

    Set a timeout for requests, so when a web page does not respond the bot does not hang.

    To make setting the user-agent string easier make it a config.ini option for anyurl. If not configured it will fallback to the default value.

    opened by jrspruitt 0
  • messages need to be reassembled before decoding utf-8

    messages need to be reassembled before decoding utf-8

    The current implementation decodes to utf-8 immediately after receiving data from the socket. (see https://github.com/jkent/jkent-pybot/blob/6c4d0da4bb2e6dfd1c5dab3bf9af11b37c9ba3e3/client.py#L102) It would be better to do the utf-8 decoding after spitting the lines up into commands so a fragmented packet won't cause data loss in the try block.

    bug 
    opened by jkent 0
  • Imgurplugin Unicode Decoding Error.

    Imgurplugin Unicode Decoding Error.

    With input of url http://imgur.com/wRdlRtS The bot crashes. The title of that image has a ♫ which seems to be the issue.

    Traceback (most recent call last): File "main.py", line 12, in core.run() File "/srv/pybot/core.py", line 24, in run self.tick() File "/srv/pybot/core.py", line 50, in tick obj.do_write() File "/srv/pybot/client.py", line 35, in do_write n = self._write(self.sendbuf) File "/srv/pybot/client.py", line 81, in _write n = self.sock.send(data) File "/usr/lib64/python2.7/ssl.py", line 198, in send v = self._sslobj.write(data) UnicodeEncodeError: 'ascii' codec can't encode character u'\u266b' in position 23: ordinal not in range(128)

    opened by jrspruitt 0
  • Songs plugin unique database exception.

    Songs plugin unique database exception.

    <class 'hook.TriggerHook'> hook error:
    Traceback (most recent call last):
      File "/srv/pybot/pybot/hook.py", line 28, in __call__
        return self.fn(*args[:self.nargs])
      File "/srv/pybot/plugins/song_plugin.py", line 210, in song_fix_artist_trigger
        self.cur.execute(query, (artist_id, track_id))
    sqlite3.IntegrityError: columns artist_id, name are not unique
    

    Caused when fixing song artist, when the title already exists under the fixed artist.

    opened by jrspruitt 0
Releases(v1.0.2)
Owner
Jeff Kent
Jeff Kent
Telegram Bot to Connect Strangers

Telegram Bot to Connect Strangers How to Run Set your telegram bot token as environment variable TELEGRAM_BOT_TOKEN: export TELEGRAM_BOT_TOKEN=your_t

PyTopia 12 Dec 24, 2022
Aqui está disponível GRATUITAMENTE, um bot de discord feito em python, saiba que, terá que criar seu bot como aplicação, e utilizar seu próprio token, e lembrando, é um bot básico, não se utiliza Cogs nem slash commands nele!

BotDiscordPython Aqui está disponível GRATUITAMENTE, um bot de discord feito em python, saiba que, terá que criar seu bot como aplicação, e utilizar s

Matheus Muguet 4 Feb 05, 2022
The official command-line client for spyse.com

Spyse CLI The official command-line client for spyse.com. NOTE: This tool is currently in the early stage beta and shouldn't be used in production. Yo

Spyse 43 Dec 08, 2022
Facebook fishing on telegram bot

Facebook-fishing Facebook fishing on telegram bot تثبيت الاداة pkg update -y pkg upgrade -y pkg install git -y pkg install python -y git clone https:/

sadamalsharabi 7 Oct 18, 2022
Discord Bot written in Python that plays music in your voice channel

Discord Bot that plays music! I decided to create a simple Discord bot using Python in order to advance my coding skills. Please don't ask me for help

Eric Yeung 39 Jan 01, 2023
A stable and Fast telegram video convertor bot which can compress, convert(video into audio and other video formats), rename with permanent thumbnail and trim.

ᴠɪᴅᴇᴏ ᴄᴏɴᴠᴇʀᴛᴏʀ A stable and Fast telegram video convertor bot which can compress, convert(video into audio and other video formats), rename and trim.

Mahesh Chauhan 183 Jan 04, 2023
Listen to the radio station from your favorite broadcast

Latest news Listen to the radio station from your favorite broadcast MyCroft Radio Skill for testing and copy at docker skill About Play regional radi

1 Dec 22, 2021
Discondelete, is a Discord self-bot to delete dm's or purge all messages from a guild.

Discondelete Discondelete, is a Discord self-bot to delete dm's or purge all messages from a guild. Report Bug · Request Feature Table of Contents Abo

core 4 Feb 28, 2022
This Python script will automate the process of uploading your project to GitHub.

ProjectToGithub This Python script will help you to upload your project to Github without having to type in any commands !!! Quick Start guide First C

Imira Randeniya 1 Sep 11, 2022
With Google Drive API. My computer and my phone are in love now.

Channel trought Google Drive Google Drive API In this case, "Google Drive App" is the program. To install everything you need(has some extra things),

Luis Quiñones Requelme 1 Dec 15, 2021
Discord Bot for League of Legends live match tracker

SABot Dicord Bot for League of Legends match auto tracker Features: Search Summoners statistics in League of Legends. Auto-notifications provide when

Jungyu Choi 4 Sep 27, 2022
A simple python discord bot which give you a yogurt brand name, basing on a large database often updated.

YaourtBot A discord simple bot by Lopinosaurus Before using this code : ・Move env file to .env ・Change the channel ID on line 38 of bot.py to your #pi

The only one bunny who can dev. 0 May 09, 2022
Microservice to extract structured information on EVM smart contracts.

Contract Serializer Microservice to extract structured information on EVM smart contract. Why? Modern NFT contracts may have different names for getPr

WeBill.io 8 Dec 19, 2022
wyscoutapi is an extremely basic API client for the Wyscout API (v2 & v3) for Python

wyscoutapi wyscoutapi is an extremely basic API client for the Wyscout API (v2 & v3). Usage Install with pip install wyscoutapi. To connect to the Wys

Ben Torvaney 11 Nov 22, 2022
Buscar y descargar canciones de YouTube automáticamente desde la web

🎶 DescargarCanciones 🎶 Buscar y descargar canciones o playlist de Spotify o YouTube automáticamente con todos los metadatos de la canciones en forma

1 Dec 20, 2021
A Discord Bot that tracks and displays cryptocurrencies using the CoinMarketCap API

PyBo - A Crypto Inspired Discord Bot Pybo (paɪ boʊ) is a Discord bot that utilizes the discord.py API wrapper to run the bot. Pybo also integrates the

0 Nov 17, 2022
a discord bot for searching your movies, and bot return movie url for you :)

IMDb Discord Bot how to run this bot. the first step you must create prefixes.json file the second step you must create a virtualenv if you use window

Mehdi Radfar 6 Dec 20, 2022
Grocy-create-product - A script supports the batch creation of new products in Grocy

grocy-create-product This script supports the batch creation of new products in

André Heuer 6 Jul 28, 2022
Simple PoC script that allows you to exploit telegram's "send with timer" feature by saving any media sent with this functionality.

Simple PoC script that allows you to exploit telegram's "send with timer" feature by saving any media sent with this functionality.

Matteo 52 Nov 29, 2022
PyFacebook

== PyFacebook == PyFacebook is a Python client library for the Facebook API. Samuel Cormier-Iijima ( Samuel Cormier-Iijima 573 Dec 20, 2022