Made config global

This commit is contained in:
REDNBLACK 2016-11-12 16:56:42 +03:00
parent 35b65126f9
commit 4d2cbbc063
11 changed files with 45 additions and 66 deletions

7
run.py
View File

@ -1,22 +1,19 @@
import logging.config
import configparser
from src.bot import Bot
from orator.orm import Model
from orator import DatabaseManager
from src import config
def main():
config = configparser.ConfigParser()
config.read('./main.cfg', encoding='utf-8')
logging.basicConfig(level=config['logging']['level'])
logging.getLogger("telegram.bot").setLevel(logging.ERROR)
logging.getLogger("telegram.ext").setLevel(logging.ERROR)
Model.set_connection_resolver(DatabaseManager({'db': config['db']}))
Bot(config).run()
Bot().run()
if __name__ == '__main__':
main()

View File

@ -1,3 +1,5 @@
import configparser
from src.chat_purge_queue import ChatPurgeQueue
chat_purge_queue = ChatPurgeQueue()
config = configparser.ConfigParser()
config.read('./main.cfg', encoding='utf-8')

View File

@ -4,26 +4,21 @@ from telegram.ext import Updater
from src.handlers.message_handler import MessageHandler
from src.handlers.command_handler import CommandHandler
from src.handlers.status_handler import StatusHandler
from . import chat_purge_queue
from src import ChatPurgeQueue
from . import config
class Bot:
def __init__(self, config):
self.config = config
def __init__(self):
self.updater = Updater(token=config['bot']['token'])
self.dispatcher = self.updater.dispatcher
def run(self):
logging.info("Bot started")
chat_purge_queue.init(
queue=self.updater.job_queue,
default_interval=self.config['bot']['purge_interval']
)
self.dispatcher.add_handler(MessageHandler(self.config))
self.dispatcher.add_handler(CommandHandler(self.config))
self.dispatcher.add_handler(StatusHandler(self.config))
self.dispatcher.add_handler(MessageHandler())
self.dispatcher.add_handler(CommandHandler())
self.dispatcher.add_handler(StatusHandler(chat_purge_queue=ChatPurgeQueue(self.updater.job_queue)))
self.updater.start_polling()
self.updater.idle()

View File

@ -1,23 +1,20 @@
import logging
from telegram.ext import Job
from src.entity.chat import Chat
from src import config
class ChatPurgeQueue:
queue = None
default_interval = 99999.0
jobs = {}
default_interval = float(config['bot']['default_interval'])
# TODO. Должно взять все задачи из таблицы и проинициализировать их
def init(self, queue, default_interval):
def __init__(self, queue):
self.queue = queue
self.default_interval = float(default_interval)
def add(self, chat_id, interval=None):
if interval is None:
interval = self.default_interval
def add(self, chat_id, interval=default_interval):
if self.queue is None:
logging.error("Queue is not set!")
return
@ -41,10 +38,7 @@ class ChatPurgeQueue:
job = self.jobs.pop(chat_id)
job.schedule_removal()
def __make_purge_job(self, chat_id, interval=None):
if interval is None:
interval = self.default_interval
def __make_purge_job(self, chat_id, interval=default_interval):
return Job(self.__purge_callback, interval, repeat=False, context=chat_id)
def __purge_callback(self, bot, job):

View File

@ -1,8 +1,7 @@
class Command:
def __init__(self, chat, message, config):
def __init__(self, chat, message):
self.chat = chat
self.message = message
self.config = config
self.name = Command.parse_name(message)
self.args = Command.parse_args(message)

View File

@ -1,12 +1,12 @@
import random
from src.utils import deep_get_attr
from src import config
class Message:
def __init__(self, chat, message, config):
def __init__(self, chat, message):
self.chat = chat
self.message = message
self.config = config
if self.has_text():
self.text = message.text
@ -37,7 +37,7 @@ class Message:
def has_anchors(self):
"""Returns True if the message contains at least one anchor from anchors config.
"""
anchors = self.config['bot']['anchors'].split(',')
anchors = config['bot']['anchors'].split(',')
return self.has_text() and \
(any(x in self.message.text.split(' ') for x in anchors))
@ -51,12 +51,12 @@ class Message:
"""
user_name = deep_get_attr(self.message, 'reply_to_message.from_user.username')
return user_name == self.config['bot']['name']
return user_name == config['bot']['name']
def is_random_answer(self):
"""Returns True if reply chance for this chat is high enough
"""
return random.randint(0, 100) < getattr(self.chat, 'random_chance', self.config['bot']['default_chance'])
return random.randint(0, 100) < getattr(self.chat, 'random_chance', config['bot']['default_chance'])
def __get_words(self):
text = list(self.text)

View File

@ -1,22 +1,22 @@
from src.utils import deep_get_attr
from src import config
class Status:
def __init__(self, chat, message, config):
def __init__(self, chat, message):
self.chat = chat
self.message = message
self.config = config
def is_bot_kicked(self):
"""Returns True if the bot was kicked from group.
"""
user_name = deep_get_attr(self.message, 'left_chat_member.username')
return user_name == self.config['bot']['name']
return user_name == config['bot']['name']
def is_bot_added(self):
"""Returns True if the bot was added to group.
"""
user_name = deep_get_attr(self.message, 'new_chat_member.username')
return user_name == self.config['bot']['name']
return user_name == config['bot']['name']

View File

@ -7,15 +7,12 @@ import src.entity.reply
import src.entity.chat
import src.entity.word
from src.utils import *
from src import config
class Pair(Model):
__guarded__ = ['id']
# TODO Move to config
end_sentence = '.....!!?'
all = '.!?,;:()\"'
@has_many
def replies(self):
return src.entity.reply.Reply
@ -53,7 +50,7 @@ class Pair(Model):
words = [None]
for word in message.words:
words.append(word)
if word[-1] in Pair.end_sentence:
if word[-1] in config['grammar']['end_sentence']:
words.append(None)
if words[-1] is not None:
words.append(None)
@ -125,8 +122,8 @@ class Pair(Model):
break
sentence = ' '.join(sentences).strip()
if sentence[-1:] not in Pair.end_sentence:
sentence += random.choice(list(Pair.end_sentence))
if sentence[-1:] not in config['grammar']['end_sentence']:
sentence += random.choice(list(config['grammar']['end_sentence']))
return sentence

View File

@ -6,9 +6,8 @@ from src.domain.command import Command
class CommandHandler(Handler):
def __init__(self, config):
def __init__(self):
super(CommandHandler, self).__init__(self.handle)
self.config = config
self.commands = {
'start': self.__start_command,
'help': self.__help_command,
@ -34,7 +33,7 @@ class CommandHandler(Handler):
def handle(self, bot, update):
try:
chat = Chat.get_chat(update.message)
command = Command(chat=chat, message=update.message, config=self.config)
command = Command(chat=chat, message=update.message)
callback = self.commands[command.name]
callback(update, command)

View File

@ -8,16 +8,14 @@ from src.entity.chat import Chat
class MessageHandler(ParentHandler):
def __init__(self, config):
def __init__(self):
super(MessageHandler, self).__init__(
Filters.text | Filters.sticker,
self.handle)
self.config = config
def handle(self, bot, update):
chat = Chat.get_chat(update.message)
message = Message(chat=chat, message=update.message, config=self.config)
message = Message(chat=chat, message=update.message)
if message.has_text():
logging.debug("[Chat %s %s bare_text] %s" %

View File

@ -4,35 +4,33 @@ from telegram.ext import MessageHandler, Filters
from src.domain.status import Status
from src.entity.chat import Chat
from src import chat_purge_queue
class StatusHandler(MessageHandler):
def __init__(self, config):
def __init__(self, chat_purge_queue):
super(StatusHandler, self).__init__(
Filters.status_update,
self.handle,
pass_job_queue=True)
self.handle)
self.config = config
self.chat_purge_queue = chat_purge_queue
def handle(self, bot, update, job_queue):
def handle(self, bot, update):
chat = Chat.get_chat(update.message)
status = Status(chat=chat, message=update.message, config=self.config)
status = Status(chat=chat, message=update.message)
if status.is_bot_added():
return self.__process_bot_add(status, job_queue)
return self.__process_bot_add(status)
elif status.is_bot_kicked():
return self.__process_bot_kick(status, job_queue)
return self.__process_bot_kick(status)
def __process_bot_kick(self, status, job_queue):
def __process_bot_kick(self, status):
logging.debug("[Chat %s %s bot_kicked]" %
(status.chat.chat_type, status.chat.telegram_id))
chat_purge_queue.add(status.chat.id)
self.chat_purge_queue.add(status.chat.id)
def __process_bot_add(self, status, job_queue):
def __process_bot_add(self, status):
logging.debug("[Chat %s %s bot_added]" %
(status.chat.chat_type, status.chat.telegram_id))
chat_purge_queue.remove(status.chat.id)
self.chat_purge_queue.remove(status.chat.id)