pgbot/pgbotlib/response.py

122 lines
4.2 KiB
Python
Raw Normal View History

import random
2023-10-31 01:45:36 +02:00
import re
import telethon
import yaml
import pgbotlib.api
import pgbotlib.dbstuff
import pgbotlib.misc
2023-10-31 01:45:36 +02:00
def get_token(token_name: str, token_regex: list) -> tuple:
regex = []
for i in token_regex:
regex.append(re.compile(i))
return token_name, regex
def get_tokens(path: str) -> list:
with open(path, 'r', encoding='utf-8') as data:
tokens = yaml.safe_load(data.read())
return [get_token(i, tokens[i]) for i in tokens]
class Responder:
def __init__(self, config: dict,
client: telethon.TelegramClient,
db_connection: pgbotlib.dbstuff.DBConn,
namegen: pgbotlib.misc.NameGenerator) -> None:
2023-10-31 01:45:36 +02:00
# apiregex matches "{apiname}optional data"
# message itself is also passed to the api call method
self.enabled = True
2023-10-31 01:45:36 +02:00
self.apiregex = re.compile(r'^\{(\w+)\}(.+)?$')
self.namegen = pgbotlib.misc.NameGenerator(config, db_connection)
self.tokens = get_tokens(config.get('response_tokens', 'tokens.yml'))
self.chats = config['chats']
2023-10-31 01:45:36 +02:00
self.api = pgbotlib.api.ApiWrapper(self.tokens, db_connection)
self.db_connection = db_connection
self.client = client
def tokenize(self, message: str) -> frozenset:
2023-10-31 01:45:36 +02:00
tokens = set()
for token, regexi in self.tokens:
for regex in regexi:
if regex.search(message):
tokens.add(token)
break
return frozenset(tokens)
def __get_keys(self) -> dict:
result = {}
query = 'SELECT DISTINCT tokens FROM responses'
for i in self.db_connection.query_raw(query, tuple()):
result[frozenset(i[0].split(','))] = i[0]
return result
def __response_choice(self, key: str) -> str:
return self.db_connection.query_random(
"SELECT response FROM responses WHERE tokens = %s", (key,))
def enable(self) -> None:
self.enabled = True
2023-10-31 01:45:36 +02:00
def disable(self) -> None:
self.enabled = False
def is_enabled(self) -> bool:
return self.enabled
2023-10-31 01:45:36 +02:00
def get_response(self, tokens: frozenset) -> str:
counter = 0
keys = self.__get_keys()
for items, string in keys.items():
if items <= tokens:
# check for priority tokens
for token in items:
if token.startswith('!'):
return self.__response_choice(string)
match_length = len(items & tokens)
if match_length > counter:
counter = match_length
key = string
if not counter:
return None
return self.__response_choice(key)
def api_match(self, response: str, message: str) -> str:
match = self.apiregex.search(response)
if not match:
return response
api_spec = match.groups()
return self.api.call(*api_spec, message)
2024-11-21 15:44:58 +02:00
async def template(self, response: str,
2023-10-31 01:45:36 +02:00
event: telethon.events.common.EventBuilder) -> str:
2024-11-21 15:44:58 +02:00
result = response
if '<username>' in response:
sender = await event.get_sender()
2024-11-21 15:57:28 +02:00
result = result.replace('<username>', sender)
2024-11-21 15:48:34 +02:00
result += ' I AM TEST'
2024-11-21 15:44:58 +02:00
if '<randomname>' in response:
peer_id = event.message.peer_id
users = await self.client.get_participants(entity=peer_id)
2024-11-21 15:57:28 +02:00
victim = random.choice(users)[0]
result = result.replace('<randomname>', victim)
2024-11-21 15:44:58 +02:00
return result
2023-10-31 01:45:36 +02:00
async def respond(self,
event: telethon.events.common.EventBuilder) -> None:
if not self.enabled:
2023-10-31 01:45:36 +02:00
return None
2023-11-05 17:05:06 +02:00
chat_id = telethon.utils.get_peer_id(event.message.peer_id)
if chat_id not in self.chats:
return None
2023-10-31 01:45:36 +02:00
message = event.message.text.lower()
tokens = self.tokenize(message)
2023-10-31 01:45:36 +02:00
response = self.get_response(tokens)
if not response:
return None
response = self.api_match(response, message)
2024-11-21 15:44:58 +02:00
response = await self.template(response, event)
2023-10-31 01:45:36 +02:00
await self.client.send_message(event.message.peer_id, response)