A little python library for building bots for Express
Project description
pybotx
A little python library for building bots for Express
Introduction
pybotx
is a toolkit for building bots for Express providing a mechanism for simple integration with your favourite web frameworks.
Main features:
- Simple integration with your web apps.
- Synchronous API as well as asynchronous.
- 100% test coverage.
- 100% type annotated codebase.
Requirements
Python 3.6+
pybotx
use the following libraries:
- Pydantic for the data parts.
- Requests for making synchronous calls to BotX API.
- Aiohttp for making asynchronous calls to BotX API.
- Aiojobs for dispatching asynchronous tasks.
Installation
$ pip install botx
You will also need a web framework to create bots as the current BotX API only works with webhooks. This documentation will use FastAPI for the examples bellow.
$ pip install fastapi uvicorn
Example
Let's create a simple echo bot.
- Create a file
main.py
with following content:
from botx import Bot, Message, Status
from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware
from starlette.status import HTTP_202_ACCEPTED
bot = Bot(disable_credentials=True)
@bot.default_handler
def echo_handler(message: Message, bot: Bot):
bot.answer_message(message.body, message)
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/status", response_model=Status)
def bot_status():
return bot.status
@app.post("/command", status_code=HTTP_202_ACCEPTED)
def bot_command(message: Message):
bot.execute_command(message.dict())
Or use async def
from botx import AsyncBot, Message, Status
from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware
from starlette.status import HTTP_202_ACCEPTED
bot = AsyncBot(disable_credentials=True)
@bot.default_handler
async def echo_handler(message: Message, bot: Bot):
await bot.answer_message(message.body, message)
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.add_event_handler("startup", bot.start)
app.add_event_handler("shutdown", bot.stop)
@app.get("/status", response_model=Status)
async def bot_status():
return bot.status
@app.post("/command", status_code=HTTP_202_ACCEPTED)
async def bot_command(message: Message):
await bot.execute_command(message.dict())
- Deploy a bot on your server using uvicorn and set the url for the webhook in Express.
$ uvicorn main:app --host=0.0.0.0
This bot will send back every your message.
License
This project is licensed under the terms of the MIT license.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
botx-0.11.3.tar.gz
(15.6 kB
view hashes)
Built Distribution
botx-0.11.3-py3-none-any.whl
(18.6 kB
view hashes)