Package: xbotlib
xbotlibXMPP bots for humansstatus: experimentalA friendly lightweight wrapper aroundslixmppfor writing XMPP bots in Python. The
goal is to make writing and running XMPP bots easy and fun.xbotlibis asingle file implementationwhich can easily be understood and
extended. Thexbotlibsource code and ideas are largely borrowed from the
XMPP bot experiments going on inVaria.InstallGetting StartedWorking with your botDocumentationCommandsAvatarsConfigurationUsing the.confconfiguration fileUsing the command-line interfaceUsing the environmentStorage back-endLoading PluginsServing HTTPInvitationsAPI ReferenceBot.direct(message)Bot.group(message)Bot.serve(request)Bot.routes()Bot.setup()SimpleMessageBotChatroomMore ExamplesDeploy your botsRoadmapChangesLicenseContributingInstall$pipinstallxbotlibGetting StartedPut the following in aecho.pyfile. This bot echoes back whatever message
you send it in both direct messages and group messages. In group chats, you
need to message the bot directly (e.g.echobot: hi) (seethe commands
sectionfor more).fromxbotlibimportBotclassEchoBot(Bot):defdirect(self,message):self.reply(message.text,to=message.sender)defgroup(self,message):self.reply(message.content,room=message.room)EchoBot()And thenpython echo.py. You will be asked a few questions in order to load
the account details that your bot will be using. This will generate anechobot.conffile in the same working directory for further use. See theconfigurationsection for more.That's it! If you want to go further, continue readinghere.Working with your botThe following sections try to cover all the ways you can configure and extend
your bot usingxbotlib. If anything is unclear, please let us knowon the
chat.DocumentationAdd ahelp = "my help"to yourBotclass like so.classMyBot(Bot):help="""This is my cool help.I can list some commands too:@foo - some command"""Your bot will then respond tomybot: @helpinvocations. This string can be a
multi-line string with indentation.xbotlibwill try to format this sensibly
for showing in chat clients.See more in thecommandssection for more.CommandsUsing@<command>in direct messages and<nick>, @<command>(the,is
optional, anything will be accepted here and there doesn't seem to be a
consensus on what is most common way to "at" another user in XMPP) in group chats,
here are the supported commands.@uptime: how long the bot has been running@help: the help text for what the bot doesThere are also more general status commands which all bots respond to.@bots: status check on who is a bot in the group chatThese commands will be detected in any part of the message sent to the bot. So
you can writeechobot, can we see your @uptime, orI'd love to know which @bots are here.AvatarsBy default,xbotlibwill look for anavatar.png(so far tested with.pngbut other file types may work) file alongside your Python script which contains
your bot implementation. You can also specify another path using the--avataroption on the command-line interface. The images should ideally have a height
of64and a width of64pixels each.ConfigurationAll the ways you can pass configuration details to your bot. There are three
ways to configure your bot, the configuration file, command-line interface and
the environment. Use whichever one suits you best. The values are loaded in the
following order: command-line > configuration file > environment. This means
you can override everything from the command-line easily.Using the.confconfiguration fileIf you run simply run your Python script which contains the bot thenxbotlibwill generate a configuration for you by asking a few questions. This is the
simplest way to run your bot locally.account: the account of the botpassword: the password of the bot accountnick: the nickname of the botavatar: the avatar of the bot (default:avatar.png)redis_url: the Redis connection URLrooms: a list of rooms to automatically join (comma separated)no_auto_join: disable auto-join when invited (default:False)template: the port to serve from (default:index.html.j2)serve: turn on the web server (default:False)port: the port to serve from (default:8080)storage: storage back-end (default:file)output: path to the output directory (default:./)Using the command-line interfaceEvery bot accepts a number of comand-line arguments to load configuration. You
can use the--helpoption to see what is available (e.g.python bot.py --help).-h, --help: show this help message and exit-d, --debug: enable verbose debug logs-a ACCOUNT, --account ACCOUNT: account for the bot account-p PASSWORD, --password PASSWORD: password for the bot account-n NICK, --nick NICK: nickname for the bot account-av AVATAR, --avatar AVATAR: avatar for the bot account (default:avatar.png)-ru REDIS_URL, --redis-url REDIS_URL: redis storage connection URL-r ROOMS [ROOMS ...], --rooms ROOMS [ROOMS ...]: Rooms to automatically join-naj, --no-auto-join: disable automatically joining rooms when invited (default:False)-pt PORT, --port PORT: the port to serve from (default:8080)-t TEMPLATE, --template TEMPLATE: the template to render (default:index.html.j2)-s, --serve: turn on the web server (default:False)-st {file,redis}, --storage {file,redis}: choice of storage back-end (default:file)-o OUTPUT, --output OUTPUT: path to the output directory (default:./)Using the environmentxbotlibwill try to read the following configuration values from the
environment if it cannot read them from a configuration file or the
command-line interface. This can be useful when doing remote server
deployments.XBOT_ACCOUNT: The bot accountXBOT_PASSWORD: The bot passwordXBOT_NICK: The bot nicknameXBOT_AVATAR: The bot avatar icon (default:avatar.png)XBOT_REDIS_URL: Redis key store connection URLXBOT_ROOMS: The rooms to automatically joinXBOT_NO_AUTO_JOIN: Disable auto-joining on invite (default:False)XBOT_TEMPLATE: the template to render (default:index.html.j2)XBOT_SERVE: Turn on the web server (default:False)XBOT_PORT: The port to serve from (default:8080)XBOT_STORAGE: choice of storage back-end (default:file)XBOT_OUTPUT: path to the output directory (default:./)Storage back-endIn order to store data you can make use of theself.dbattribute of theBotclass. It is a Python dictionary which will be saved to disk automatically for
you as a<nick>.jsonin your current working directory. The name and path to
this file can be configured using the output option (e.g.python bot.py --output /var/www/html)defgroup(self,message):ifnotmessage.roominself.db.keys():self.db[message.room]="visited"If you want to inspect the database when the bot is not running, you can look
in the file directly.$cat<nick>.jsonFor more advanced use cases,xbotlibalso supportsRedisas a storage back-end. You'll need to configure this (e.g.--storage redis)
as the default uses the filesystem approach mentioned above. The sameself.dbwill then be passed as a Redis connection object. You will also need to install
additional dependencies usingpip install xbotlib[redis].Loading PluginsYou can specify aplugins = [...]on your bot definition and they will be
automatically loaded when you start your bot.classMyBot(Bot):plugins=["xep_0066"]Seeherefor the list of supported plugins.Serving HTTPFirstly, you'll need to install additional dependencies.$pipinstallxbotlib[web]Your bot will run a web server if you configure it to do so. Use the--serveoption on the command-line, theserve = Trueconfiguration option or theXBOT_SERVE=Trueenvironment variable.If you're running your bot locally, just visit0.0.0.0:8080to see. The default response is just some
placeholder text. You can write your own responses using theBot.servefunction.xbotlibprovides a small wrapper API forJinja2which allows you to
easily template and generate HTML. The web server is provided byaiohttp.The default template search path isindex.html.j2in the current working
directory. This can be configured through the usual configuration entrypoints.
It is possible to use the template without the built-in server too!Here's a small example that renders a random ASCII letter and uses a stylesheet.index.html.j2<html><head><style> h1 { color: red; } </style></head><body><h1>{{letter}}</h1></body></html>bot.pyfromstringimportascii_lettersasyncdefserve(self,request):letter=choice(ascii_letters)rendered=self.template.render(letter=letter)returnself.respond(rendered)Please note the use of thereturnkeyword here. Theservefunction must
return a response that will be passed to the web server. Also, theasynckeyword. This function can handle asynchronous operations and must be marked as
such. You can return any content type that you might find on the web (e.g.
HTML, XML, JSON, audio and maybe even video) but you must specify thecontent_type=...keyword argument forrespond.See thelist of available content
typesfor more.If you want to pass data from yourdirect/groupfunctions to theservefunction, you'll need to make use ofsome type of persistent
storage. Yourservefunction can read from the storage
back-end and then respond. This is usually as simple as accessing theself.dbattribute.InvitationsAs long as the--no-auto-joinoption is not set (via the configuration file
or environment also), then your bot will automatically join any room it is
invited to. Rooms that your bot has been invited to will be stored in the.xbotlib/data.jsonfile. If your bot is turned off or fails for some reason
then it will read this file when turned back on to see what rooms it should
re-join automatically. Thedata.jsonfile can be edited freely by hand.API ReferenceWhen writing your own bot, you always sub-class theBotclass provided fromxbotlib. Then if you want to respond to a direct message, you write adirectfunction. If you want to respond to a group chat
message, you write agroupfunction. That's it for the
basics.Bot.direct(message)Respond to direct messages.Arguments:message: received message (seeSimpleMessagebelow for available attributes)Bot.group(message)Respond to a message in a group chat.Arguments:message: received message (seeSimpleMessagebelow for available attributes)Bot.serve(request)Serve requests via the built-in web server.Seethis sectionfor more.Arguments:request: the web requestBot.routes()Register additional routes for web serving.Seethis sectionfor more.This is an advanced feature. Useself.web.add_routes.fromaiohttp.webimportgetdefroutes(self):self.web.add_routes([get("/foo",self.foo)])Bot.setup()Run some setup logic before starting your bot.SimpleMessageA simple message interface.Attributes:text: the entire text of the messagecontent: the text of the message after the nicksender: the user the message came fromroom: the room the message came fromreceiver: the receiver of the messagenick: the nickname of the sendertype: the type of messageurl: The URL of a sent fileBotBot.reply(message, to=None, room=None)Send a reply back.Arguments:message: the message that is sentto: the user to send the reply toroom: the room to send the reply toBot.respond(response, content_type="text/html")Return a response via the web server.Arguments:response: the text of the responsecontent_type: the type of responseOther useful attributes on theBotclass are:self.db: Thestorage back-endChatroomWe're lurking inxbotlibtest@muc.vvvvvvaria.orgif
you want to chat or just invite your bots for testing.More ExamplesSee more examples ongit.vvvvvvaria.org.Deploy your botsDocumentation comingsoon.RoadmapSee theissue tracker.ChangesSee theCHANGELOG.md.LicenseSee theLICENSE.ContributingAny and all contributions most welcome! Happy to hear how you use the library
or what could be improved from a usability perspective.To test, installTox(pip install tox) and runtoxto run the test suite locally.