This commit is contained in:
retoor 2025-05-10 21:52:53 +02:00
parent 1857f18d3d
commit dad15557df
2 changed files with 52 additions and 95 deletions
src
snekbot.egg-info
snekbot

View File

@ -10,130 +10,84 @@ License-File: LICENSE.txt
Requires-Dist: aiohttp
Dynamic: license-file
# Snekbot API
# SnekBot: Your Instant Chat Companion
This is the Snekbot API. This document describes how to create a bot responding to "hello", "bye" and "@username-of-bot".
## Create Your Own Bot in Minutes
## 5 minute tutorial
### Overview
SnekBot is designed for rapid deployment and customization, providing a fully asynchronous and production-ready chat bot solution. It is built to handle network issues effectively, ensuring a reliable user experience.
Literally.
### Prerequisites
- Python 3.8 or higher
- Basic understanding of Python programming
### Installation
#### Requirements:
Python:
- python3
- python3-venv
- python3-pip
Use apt or your package manager to install these packages. There is a big chance your system already has them.
### Installation Instructions
For Debian (Ubuntu): `sudo apt install python3 python3-venv python3-pip -y`
#### 1. Prepare Your Environment
```bash
# For Ubuntu/Debian users:
sudo apt install python3 python3-venv python3-pip -y
#### Environment
- `python3 -m venv venv`
- `source venv/bin/activate`
- `pip install git+https://molodetz.nl/retoor/snekbot.git`
# Create a virtual environment for your bot
python3 -m venv venv
source venv/bin/activate
```
#### Create account
Create regular user account for your bot. You need this later in your script.
Make sure you have this information right now:
- bot username
- bot password
- bot url (wss://your-snek-instance.com/rpc.ws)
#### 2. Install SnekBot
```bash
pip install git+https://molodetz.nl/retoor/snekbot.git
```
#### Create a file
Open a file ending with the `.py` extension and paste this content. Replace the authentication details on the bottom lines with the one of the account you just created.
### Bot Development
To create your bot, use the following template:
```python
import asyncio
from snekbot.bot import Bot
class ExampleBot(Bot):
class CustomSnekBot(Bot):
async def on_join(self, channel_uid):
await super().on_join(channel_uid)
print(f"I joined!")
await self.send_message(
channel_uid,
f"Hello, i'm actively part of the conversation in channel {channel_uid} now, you don't have to mention me anymore. ",
"Hello! I am here to assist you."
)
async def on_leave(self, channel_uid):
await super().on_leave(channel_uid)
print(f"I left!!")
await self.send_message(
channel_uid, "I stop actively being part of the conversation now. Bye!"
)
async def on_ping(self, username, user_nick, channel_uid, message):
print(f"Ping from {user_nick} in channel {channel_uid}: {message}")
await self.send_message(channel_uid, "pong " + message)
async def on_own_message(self, channel_uid, data):
print(f"Received my own message: {data.message}")
async def on_mention(self, username, user_nick, channel_uid, message):
message = message[len(self.username) + 2 :]
print(f"Mention from {user_nick}: {message}")
if "source" in message:
with open(__file__) as f:
result = f.read()
result = result.replace(f'"{self.username}"', '"example username"')
result = result.replace(self.password, "example password")
result = (
"This is the actual source code running me now. Fresh from the bakery:\n\n```python\n"
+ result
+ "\n```"
)
await self.send_message(channel_uid, result)
else:
await self.send_message(
channel_uid, f'Hey {user_nick}, Thanks for mentioning me "{message}".'
)
async def on_message(self, sender_username, sender_nick, channel_uid, message):
print(f"Message from {sender_nick}: {message}")
if not self.has_joined(channel_uid):
print(f"Probably not for me since i'm not mentioned and not joined yet")
return
message = message.lower()
result = None
if "hello" in message:
result = f"Hi @{sender_nick}"
await self.send_message(channel_uid, f"Greetings, {sender_nick}!")
elif "bye" in message:
result = f"Bye @{sender_nick}"
await self.send_message(channel_uid, f"Goodbye, {sender_nick}!")
if result:
await self.send_message(channel_uid, result)
bot = ExampleBot(
url="ws://snek.molodetz.nl/rpc.ws", username="example", password="example"
# Initialize your bot
bot = CustomSnekBot(
url="wss://your-snek-instance.com/rpc.ws",
username="your_bot_username",
password="your_secure_password"
)
asyncio.run(bot.run())
```
#### Run the bot
Make sure you have (still) activated your virtual env.
### Running Your Bot
```bash
python [your-script].py
python your_bot_script.py
```
If you get the error 'python not found' or 'aiohttp not found', run `source .venv/bin/activate` again and run `python [your script].py` again.
#### Debugging
Add `import logging` and `logging.BasicConfig(level=logging.DEBUG)`.
### Event Handlers
You can override the following event handlers:
- `on_join`: Triggered when the bot joins a channel
- `on_leave`: Triggered when the bot leaves a channel
- `on_ping`: Responds to ping messages
- `on_mention`: Handles direct mentions
- `on_message`: Processes incoming messages
#### Summary
The `ExampleBot` class inherits from a base `Bot` class and implements several event handlers:
- `on_join`: Sends a welcome message when the bot joins a channel.
- `on_leave`: Sends a goodbye message when the bot leaves.
- `on_ping`: Responds with "pong" when it receives a ping message.
- `on_own_message`: Logs messages sent by the bot itself.
- `on_mention`: Handles mentions; if "source" is in the message, it replies with its own source code, with sensitive data disguised.
- `on_message`: Responds to "hello" and "bye" messages if the bot has joined the channel.
The bot will be instantiated and runs asynchronously. It will survive server deploys and network outages. If such issue occurs, it will try to reconnect within a second like nothing happened. It's production ready.
### Additional Information
- For detailed logging, include `logging.basicConfig(level=logging.DEBUG)` in your code.
- The bot is designed to automatically reconnect in case of connection drops.
- Feel free to customize the bot to meet your specific requirements.
### Contribution Guidelines
Contributions are welcome. Please submit pull requests for any enhancements or bug fixes.
### License
This project is licensed under the MIT License.

View File

@ -118,7 +118,10 @@ class Bot:
while True:
data = await rpc.receive()
if not data:
return
try:
message = data.message.strip()
except AttributeError: