Exemple #1
0
class YoutubeBot(object):

    api_token = ''

    def __init__(self):
        self.bot = TelegramBot(self.api_token)
        self.bot.get_me()
        last_updates = self.bot.get_updates(offset=0).wait()
        try:
            self.last_update_id = list(last_updates)[-1].update_id
        except IndexError:
            self.last_update_id = None
        print 'last update id: {}'.format(self.last_update_id)

    def process_message(self, message):

        text = message.message.text
        chat = message.message.chat
        text = text.strip().split('&')[0]
        msg = 'Could not download {}'.format(text)
        print 'Got message: \33[0;32m{}\33[0m'.format(text)
        try:
            self.bot.send_message(chat.id, 'Staring to download')
            with youtube_dl.YoutubeDL(YDL_OPTS) as ydl:
                r_code = ydl.download([text])
                if r_code == 0:
                    msg = '{} download successfully'.format(text)
        except Exception:
            pass
        self.bot.send_message(chat.id, msg)

    def run(self):
        print 'Main loop started'
        while True:
            updates = self.bot.get_updates(
                offset=self.last_update_id).wait()
            try:
                for update in updates:
                    if update.update_id > self.last_update_id:
                        self.last_update_id = update.update_id
                        self.process_message(update)
            except Exception as ex:
                print traceback.format_exc()
Exemple #2
0
class YoutubeBot(object):

    api_token = ''

    def __init__(self):
        self.bot = TelegramBot(self.api_token)
        self.bot.get_me()
        last_updates = self.bot.get_updates(offset=0).wait()
        try:
            self.last_update_id = list(last_updates)[-1].update_id
        except IndexError:
            self.last_update_id = None
        print 'last update id: {}'.format(self.last_update_id)

    def process_message(self, message):

        text = message.message.text
        chat = message.message.chat
        text = text.strip().split('&')[0]
        msg = 'Could not download {}'.format(text)
        print 'Got message: \33[0;32m{}\33[0m'.format(text)
        try:
            self.bot.send_message(chat.id, 'Staring to download')
            with youtube_dl.YoutubeDL(YDL_OPTS) as ydl:
                r_code = ydl.download([text])
                if r_code == 0:
                    msg = '{} download successfully'.format(text)
        except Exception:
            pass
        self.bot.send_message(chat.id, msg)

    def run(self):
        print 'Main loop started'
        while True:
            updates = self.bot.get_updates(offset=self.last_update_id).wait()
            try:
                for update in updates:
                    if update.update_id > self.last_update_id:
                        self.last_update_id = update.update_id
                        self.process_message(update)
            except Exception as ex:
                print traceback.format_exc()
Exemple #3
0
class Telegram(object):
    def __init__(self, config, interpreter):
        super().__init__()
        self.__interpreter = interpreter
        self.__logger = logging.getLogger('telegram')
        logHandler = StreamHandler()
        logHandler.setLevel(logging.DEBUG)
        self.__logger.addHandler(logHandler)

        self.__bot = TelegramBot(config['Telegram']['token'])
        self.__logger.warning("Bot details: " + str(self.__bot.get_me().wait()))

        self.__updateOffset = None

    def send_msg(self, telegram_id, text):
        self.__bot.send_message(telegram_id, text).wait()

    def getUpdates(self, dbSession):
        updates = None
        try:
            if self.__updateOffset is not None:
                updates = self.__bot.get_updates(offset=self.__updateOffset + 1).wait()
            else:
                updates = self.__bot.get_updates().wait()

            if updates is None:
                raise Exception("No updates have been received due to an error")
        except:
            return

        for update in updates:
            if hasattr(update, 'message'):
                self.__logger.warning(str(update.message.sender) + ": " + update.message.text)
                self.__interpreter.interpret(dbSession, self, update.message.sender, update.message.text.split(' '))
            if hasattr(update, 'update_id'):
                self.__updateOffset = update.update_id

    def shutdown(self):
        pass
Exemple #4
0
class NimBot(object):
    token = config.token
    
    def __init__(self):
        self.bot = TelegramBot(self.token)
        self.bot.get_me()
        last_updates = self.bot.get_updates(offset=0).wait()
        try:
            self.last_update_id = list(last_updates)[-1].update_id
        except IndexError:
            self.last_update_id = None
        print('last update id: {0}'.format(self.last_update_id))
 
    def read_current_state(self, chat_id):
        connection = pymysql.connect(host=config.sql_host,
                                     user=config.sql_user,
                                     password=config.sql_user_password,
                                     db=config.sql_db,
                                     charset=config.sql_charset,
                                     cursorclass=pymysql.cursors.DictCursor)
        try:
            with connection.cursor() as cursor:
                sql = "SELECT chat_id, num1, num2, num3 FROM data WHERE chat_id = {}".format(chat_id)
                cursor.execute(sql)
                row = cursor.fetchone()
        finally:
            cursor.close()
            connection.close()
            return row

    def write_new_user(self, chat_id, num1, num2, num3):
        connection = pymysql.connect(host=config.sql_host,
                                     user=config.sql_user,
                                     password=config.sql_user_password,
                                     db=config.sql_db,
                                     charset=config.sql_charset,
                                     cursorclass=pymysql.cursors.DictCursor)
        try:
            with connection.cursor() as cursor:
                sql = "INSERT INTO data (chat_id, num1, num2, num3) VALUES({}, {}, {}, {})".format(chat_id, num1, num2, num3)
                cursor.execute(sql)
                connection.commit()
        finally:
            cursor.close()
            connection.close()

    def write_current_state(self, chat_id, num1, num2, num3):
        connection = pymysql.connect(host=config.sql_host,
                                     user=config.sql_user,
                                     password=config.sql_user_password,
                                     db=config.sql_db,
                                     charset=config.sql_charset,
                                     cursorclass=pymysql.cursors.DictCursor)
        try:
            with connection.cursor() as cursor:
                sql = "UPDATE data SET num1={1}, num2={2}, num3={3} WHERE chat_id = {0}".format(chat_id, num1, num2, num3)
                cursor.execute(sql)
                connection.commit()
        finally:
            cursor.close()
            connection.close()

    def write_message(self, chat_id, title, username, first_name, last_name, text):
        connection = pymysql.connect(host=config.sql_host,
                                     user=config.sql_user,
                                     password=config.sql_user_password,
                                     db=config.sql_db,
                                     charset=config.sql_charset,
                                     cursorclass=pymysql.cursors.DictCursor)
        try:
            with connection.cursor() as cursor:
                sql = "INSERT INTO messages (chat_id, title, username, first_name, last_name, text) VALUES({}, '{}', '{}', '{}', '{}', '{}')".format(chat_id, title, username, first_name, last_name, text)
                cursor.execute(sql)
                connection.commit()
        finally:
            cursor.close()
            connection.close()

    def check_user_numbers(self, list_from_db, list_from_user):
        list_from_db_work = list(list_from_db)
        list_from_user_work = list(list_from_user)
        for number in list_from_user:
            if number in list_from_db_work:
                list_from_db_work.remove(number)
                list_from_user_work.remove(number)
        if len(list_from_db_work)!=1 or len(list_from_user_work)!=1:
            return -1
        elif list_from_db_work[0] < list_from_user_work[0]:
            return -2
        else:
            return 0

    def make_a_move(self, list_from_user):
        random_decision = random.randint(0,100)
        if random_decision>30:
            return self.make_a_move_smart(list_from_user)
        elif random_decision<=30:
            return self.make_a_move_random(list_from_user)

    def make_a_move_random(self, list_from_user):
        list_from_user_work = list(list_from_user)
        indexes_for_change = [0,1,2]
        for i, number in enumerate(list_from_user_work):
            if number==0:
                indexes_for_change.remove(i)
        if len(indexes_for_change)>0:
            index_for_change = random.choice(indexes_for_change)
            list_from_user_work[index_for_change] = list_from_user_work[index_for_change] - random.randint(1,list_from_user_work[index_for_change])
            return list_from_user_work
        else:
            return -1
    
    def make_a_move_smart(self, list_from_user):
        num1 = list_from_user[0]
        num2 = list_from_user[1]
        num3 = list_from_user[2]
        if num1==0 and num2==0 and num3==0:
            return -1
        elif (num1^num2^num3)==0:
            return self.make_a_move_random(list_from_user)
        else:
            list_from_user_work = list(list_from_user)
            list_of_right_answers = []
            indexes_for_change= [0,1,2]
            for i, number in enumerate(list_from_user_work):
                if number==0:
                    indexes_for_change.remove(i)
            if len(indexes_for_change)>0:
                index_for_change = random.choice(indexes_for_change)
                i = 1
                while i <= list_from_user_work[index_for_change]:
                    if index_for_change==0:
                        num1 = list_from_user[0] - i
                        num2 = list_from_user[1]
                        num3 = list_from_user[2]
                        if (num1^num2^num3)==0:
                            list_of_right_answers.append([num1, num2, num3])
                    elif index_for_change==1:
                        num1 = list_from_user[0]
                        num2 = list_from_user[1] - i
                        num3 = list_from_user[2]
                        if (num1^num2^num3)==0:
                            list_of_right_answers.append([num1, num2, num3])
                    elif index_for_change==2:
                        num1 = list_from_user[0]
                        num2 = list_from_user[1]
                        num3 = list_from_user[2] - i
                        if (num1^num2^num3)==0:
                            list_of_right_answers.append([num1, num2, num3])
                    i = i + 1
                if len(list_of_right_answers)==0:
                    indexes_for_change.remove(index_for_change)
                    if len(indexes_for_change)>0:
                        index_for_change = random.choice(indexes_for_change)
                        i = 1
                        while i <= list_from_user_work[index_for_change]:
                            if index_for_change==0:
                                num1 = list_from_user[0] - i
                                num2 = list_from_user[1]
                                num3 = list_from_user[2]
                                if (num1^num2^num3)==0:
                                    list_of_right_answers.append([num1, num2, num3])
                            elif index_for_change==1:
                                num1 = list_from_user[0]
                                num2 = list_from_user[1] - i
                                num3 = list_from_user[2]
                                if (num1^num2^num3)==0:
                                    list_of_right_answers.append([num1, num2, num3])
                            elif index_for_change==2:
                                num1 = list_from_user[0]
                                num2 = list_from_user[1]
                                num3 = list_from_user[2] - i
                                if (num1^num2^num3)==0:
                                    list_of_right_answers.append([num1, num2, num3])
                            i = i + 1
                        if len(list_of_right_answers)==0:
                            indexes_for_change.remove(index_for_change)
                            if len(indexes_for_change)>0:
                                index_for_change = random.choice(indexes_for_change)
                                i = 1
                                while i <= list_from_user_work[index_for_change]:
                                    if index_for_change==0:
                                        num1 = list_from_user[0] - i
                                        num2 = list_from_user[1]
                                        num3 = list_from_user[2]
                                        if (num1^num2^num3)==0:
                                            list_of_right_answers.append([num1, num2, num3])
                                    elif index_for_change==1:
                                        num1 = list_from_user[0]
                                        num2 = list_from_user[1] - i
                                        num3 = list_from_user[2]
                                        if (num1^num2^num3)==0:
                                            list_of_right_answers.append([num1, num2, num3])
                                    elif index_for_change==2:
                                        num1 = list_from_user[0]
                                        num2 = list_from_user[1]
                                        num3 = list_from_user[2] - i
                                        if (num1^num2^num3)==0:
                                            list_of_right_answers.append([num1, num2, num3])
                                    i = i + 1
                                if len(list_of_right_answers)==0:
                                    return self.make_a_move_random(list_from_user)
                                else:
                                    return random.choice(list_of_right_answers)    
                        else:
                            return random.choice(list_of_right_answers)    
                else:
                    return random.choice(list_of_right_answers)

    def process_message(self, message):
        text = message.message.text
        chat = message.message.chat
        text = text.strip()

        print('Got message: \33[0;32m{0}\33[0m from chat: {1}'.format(text, chat))

        try:
            if text == '/start':
                bot_answer = 'Это игра Ним.\nПеред вами три числа.\nКаждый ход вы должны уменьшить одно из чисел.\nЧтобы сделать ход просто напечатайте три числа, разделенные пробелом.\nПропустить ход нельзя.\nМожно изменить только одно число за ход.\nТот кто сделает ход 0 0 0 - победил. Т.е. нужно взять последнюю монету.\nИтак, числа:\n{} {} {}\nВаш ход.'
                try:
                    row = self.read_current_state(chat.id)
                    num1 = random.randint(config.min_random,config.max_random)
                    num2 = random.randint(config.min_random,config.max_random)
                    num3 = random.randint(config.min_random,config.max_random)
                    if (row == None):
                        self.write_new_user(chat.id, num1, num2, num3)
                    else:
                        self.write_current_state(chat.id, num1, num2, num3)
                    self.bot.send_message(chat.id, bot_answer.format(num1, num2, num3))
                except Exception:
                    self.bot.send_message(chat.id, 'Unknow error. Sorry.')
            elif text == '/help':
                bot_answer = 'Это игра Ним.\nПеред вами три числа.\nКаждый ход вы должны уменьшить одно из чисел.\nЧтобы сделать ход просто напечатайте три числа, разделенные пробелом.\nПропустить ход нельзя.\nМожно изменить только одно число за ход.\nТот кто сделает ход 0 0 0 - победил. Т.е. нужно взять последнюю монету.\n/newgame - новая игра.\n/send2admin [message] - отправить сообщение админу (140 симв.)\n'
                try:
                    self.bot.send_message(chat.id, bot_answer)
                except Exception:
                    self.bot.send_message(chat.id, 'Unknow error. Sorry.')
            elif text == '/newgame':
                bot_answer = 'Ок, начинаем новую игру:\n{} {} {}\nВаш ход.'
                try:
                    row = self.read_current_state(chat.id)
                    num1 = random.randint(config.min_random,config.max_random)
                    num2 = random.randint(config.min_random,config.max_random)
                    num3 = random.randint(config.min_random,config.max_random)
                    if (row == None):
                        self.write_new_user(chat.id, num1, num2, num3)
                    else:
                        self.write_current_state(chat.id, num1, num2, num3)
                    self.bot.send_message(chat.id, bot_answer.format(num1, num2, num3))
                except Exception:
                    self.bot.send_message(chat.id, 'Unknow error. Sorry.')
            elif '/send2admin' in text:
                bot_answer = 'Сообщение "{}" передано администратору, когда-нибудь он его обязательно прочитает.\nНапомню числа:\n{} {} {}\nВаш ход.'
                try:
                    row = self.read_current_state(chat.id)
                    num1 = random.randint(config.min_random,config.max_random)
                    num2 = random.randint(config.min_random,config.max_random)
                    num3 = random.randint(config.min_random,config.max_random)
                    if (row == None):
                        self.write_new_user(chat.id, num1, num2, num3)
                    else:
                        row = self.read_current_state(chat.id)
                        num1 = row["num1"]
                        num2 = row["num2"]
                        num3 = row["num3"]
                    if text[int(text.find('/send2admin'))+12:]=='':
                        self.bot.send_message(chat.id, 'После /send2admin нужно что-нибудь написать. Сообщение не передано.\nНапомню числа:\n{} {} {}\nВаш ход.'.format(num1, num2, num3))
                    else:
                        self.write_message(chat.id, str(chat.title), str(chat.username), str(chat.first_name), str(chat.last_name), str(text[int(text.find('/send2admin'))+12:]))
                        self.bot.send_message(chat.id, bot_answer.format(text[int(text.find('/send2admin'))+12:], num1, num2, num3))
                except Exception:
                    self.bot.send_message(chat.id, 'Unknow error. Sorry.')

            else:
                bot_answer = '{} {} {}\n'
                try:
                    result = re.split(r'[\s]', text)
                    numcount = len(result)
                    if (numcount == 3):
                        num1 = int(result[0])
                        num2 = int(result[1])
                        num3 = int(result[2])
                        list_from_user = [num1, num2, num3]
                        row = self.read_current_state(chat.id)
                        if (row == None):
                            new_list = self.make_a_move(list_from_user)
                            self.write_new_user(chat.id, new_list[0], new_list[1], new_list[2])
                            self.bot.send_message(chat.id, bot_answer.format(self.bot.send_message(chat.id, bot_answer.format(num1, num2, num3))))
                        else:
                            list_from_db = [row["num1"], row["num2"], row["num3"]]
                            result_of_check = self.check_user_numbers(list_from_db, list_from_user)
                            if result_of_check == -1:
                                self.bot.send_message(chat.id, "Error. Ошибка при обработке ответа. Нужно изменть одно число. Нельзя изменять больше, чем одно число.")
                            elif result_of_check == -2:
                                self.bot.send_message(chat.id, "Error. Ошибка при обработке ответа. Число можно изменять только в меньшую сторону.")
                            elif result_of_check == 0:
                                if list_from_user[0]==0 and list_from_user[1]==0 and list_from_user[2]==0:
                                    num1 = random.randint(config.min_random,config.max_random)
                                    num2 = random.randint(config.min_random,config.max_random)
                                    num3 = random.randint(config.min_random,config.max_random)
                                    self.write_current_state(chat.id, num1, num2, num3)
                                    self.bot.send_message(chat.id, "Вы победили! Сыграем еще? Вот новые числа:\n{} {} {}".format(num1, num2, num3))
                                else:    
                                    new_list = self.make_a_move(list_from_user)
                                    if new_list[0]==0 and new_list[1]==0 and new_list[2]==0:
                                        num1 = random.randint(config.min_random,config.max_random)
                                        num2 = random.randint(config.min_random,config.max_random)
                                        num3 = random.randint(config.min_random,config.max_random)
                                        self.write_current_state(chat.id, num1, num2, num3)
                                        self.bot.send_message(chat.id, "0 0 0\nЯ победил!\nСыграем еще? Вот новые числа:\n{} {} {}".format(num1, num2, num3))
                                    else:
                                        num1 = new_list[0]
                                        num2 = new_list[1]
                                        num3 = new_list[2]
                                        self.write_current_state(chat.id, num1, num2, num3)
                                        self.bot.send_message(chat.id, bot_answer.format(str(num1), str(num2), str(num3)))
                    else:
                        self.bot.send_message(chat.id, "Error. Ошибка при обработке ответа. Вы должны прислать три числа, разделенные одинарным пробелом. Если вы хотите написать администратору, используйте команду /send2admin")
                except Exception:
                    self.bot.send_message(chat.id, 'Unknow error. Sorry.')
        except Exception:
            pass
 
    def run(self):
        print('Main loop started')
        while True:
            updates = self.bot.get_updates(offset=self.last_update_id).wait()
            try:
                for update in updates:
                    if int(update.update_id) > int(self.last_update_id):
                        self.last_update_id = update.update_id
                        self.process_message(update)
            except Exception as ex:
                print(traceback.format_exc())
Exemple #5
0
	for i in range(1,300):
		time.sleep(0.04)
		bot.get_updates(i, limit=1)

print "Hello World!"

"""
Setup the bot
"""

bot = TelegramBot('172048491:AAG253i7GAR-AxQTX7bZlhlJmAPQu6n_3b0')
bot.set_webhook() # remove webhook
bot.update_bot_info().wait()
print(bot.username)

botUser = bot.get_me().wait()
print(botUser)

#updates = bot.get_updates(159).wait()
#for update in updates:
#	update=update

#print("update:           ", update)

#message_id = update.message.message_id;
#first_name = update.message.sender.first_name;


#print( "message_id: ", message_id)
#print( "name: ", first_name)
Exemple #6
0
class TGBot(object):
    def __init__(self, token, plugins=[], no_command=None, db_url=None):
        self._token = token
        self.tg = TelegramBot(token)
        self._last_id = None
        self.cmds = {}
        self.pcmds = {}
        self._no_cmd = no_command
        self._msgs = {}
        self._plugins = plugins

        if no_command is not None:
            if not isinstance(no_command, TGPluginBase):
                raise NotImplementedError("%s does not subclass tgbot.TGPluginBase" % type(no_command).__name__)

        for p in self._plugins:

            if not isinstance(p, TGPluginBase):
                raise NotImplementedError("%s does not subclass tgbot.TGPluginBase" % type(p).__name__)

            for cmd in p.list_commands():

                if not isinstance(cmd, TGCommandBase):
                    raise NotImplementedError("%s does not subclass tgbot.TGCommandBase" % type(cmd).__name__)

                if cmd in self.cmds or cmd in self.pcmds:
                    raise Exception(
                        "Duplicate command %s: both in %s and %s"
                        % (cmd.command, type(p).__name__, self.cmds.get(cmd.command) or self.pcmds.get(cmd.command))
                    )

                if cmd.prefix:
                    self.pcmds[cmd.command] = cmd
                else:
                    self.cmds[cmd.command] = cmd

        if db_url is None:
            self.db = connect("sqlite:///:memory:")
            models.database_proxy.initialize(self.db)
            self.setup_db()
        else:
            self.db = connect(db_url)
            self.db.autorollback = True
            models.database_proxy.initialize(self.db)

    def update_bot_info(self):
        # re-implement update_bot_info to make it synchronous
        if self.tg.username is None:
            self.tg._bot_user = self.tg.get_me().wait()

    def process_update(self, update):  # noqa not complex at all!
        self.update_bot_info()
        message = update.message

        try:
            models.User.create(
                id=message.sender.id, first_name=message.sender.first_name, last_name=message.sender.last_name
            )
        except peewee.IntegrityError:
            pass  # ignore, already exists

        if message.left_chat_participant is not None and message.left_chat_participant.username == self.tg.username:
            models.GroupChat.delete().where(models.GroupChat.id == message.chat.id).execute()
        elif isinstance(message.chat, GroupChat):
            try:
                models.GroupChat.create(id=message.chat.id, title=message.chat.title)
            except peewee.IntegrityError:
                pass

        if message.new_chat_participant is not None and message.new_chat_participant != self.me:
            try:
                models.User.create(
                    id=message.new_chat_participant.id,
                    first_name=message.new_chat_participant.first_name,
                    last_name=message.new_chat_participant.last_name,
                )
            except peewee.IntegrityError:
                pass  # ignore, already exists

        if message.contact is not None:
            try:
                models.User.create(
                    id=message.contact.user_id,
                    first_name=message.contact.first_name,
                    last_name=message.contact.last_name,
                )
            except peewee.IntegrityError:
                pass  # ignore, already exists

        if message.text is not None and message.text.startswith("/"):
            spl = message.text.find(" ")

            if spl < 0:
                cmd = message.text[1:]
                text = ""
            else:
                cmd = message.text[1:spl]
                text = message.text[spl + 1 :]

            spl = cmd.find("@")
            if spl > -1:
                cmd = cmd[:spl]

            self.process(message, cmd, text)
        else:
            was_expected = False
            for p in self._plugins:
                was_expected = p.is_expected(self, message)
                if was_expected:
                    break

            if self._no_cmd is not None and not was_expected:
                self._no_cmd.chat(self, message, message.text)

    def setup_db(self):
        models.create_tables(self.db)

    def run(self, polling_time=2):
        from time import sleep

        # make sure all webhooks are disabled
        self.tg.set_webhook().wait()

        while True:
            ups = self.tg.get_updates(offset=self._last_id).wait()
            if isinstance(ups, Error):
                print "Error: ", ups
            else:
                for up in ups:
                    self.process_update(up)
                    self._last_id = up.update_id + 1

            sleep(polling_time)

    def run_web(self, hook_url, **kwargs):
        from .webserver import run_server

        url = hook_url
        if url[-1] != "/":
            url += "/"
        self.tg.set_webhook(url + "update/" + self._token)
        run_server(self, **kwargs)

    def list_commands(self):
        return self.cmds.values() + self.pcmds.values()

    def print_commands(self, out=sys.stdout):
        """
        utility method to print commands
        and descriptions for @BotFather
        """
        cmds = self.list_commands()
        for ck in cmds:
            if ck.printable:
                out.write("%s\n" % ck)

    def process(self, message, cmd, text):
        if cmd in self.cmds:
            self.cmds[cmd].method(self, message, text)
        elif cmd in self.pcmds:
            self.pcmds[cmd].method(self, message, text)
        else:
            for pcmd in self.pcmds:
                if cmd.startswith(pcmd):
                    ntext = cmd[len(pcmd) :]
                    if text:
                        ntext += " " + text
                    self.pcmds[pcmd].method(self, message, ntext)
                    break
Exemple #7
0
class DigestBot(object):
    token = '309819985:AAE03f1oaX1VvfeqxKtcghq7aoNZSEuYTEw'
    stack_list = []
    admin = 'Greg'
    userID = 0

    def __init__(self):
        self.bot = TelegramBot(self.token)
        self.bot.get_me()
        last_updates = self.bot.get_updates(offset=0).wait()
        try:
            self.last_update_id = list(last_updates)[-1].update_id
        except IndexError:
            self.last_update_id = None
        print('last update id: {0}'.format(self.last_update_id))

    def process_message(self, message):
        text = message.message.text
        chat = message.message.chat
        text = text.strip()
        digest_tag = '#digest'
        print('Got message: \33[0;32m{0}\33[0m from chat: {1}'.format(
            text, chat))
        try:
            if text == '/digest':
                bot_answer = 'There is your digest:\n'
                try:
                    for struct in self.stack_list:
                        if struct['chat_id'] == chat.id:
                            bot_answer += struct['chat_message']
                            bot_answer += '\n'
                    bot_answer = bot_answer[:-1]
                    bot_answer += '.'
                    self.bot.send_message(chat.id, bot_answer)
                except Exception:
                    self.bot.send_message(chat.id, 'Unknow error. Sorry.')
            if text == '/stackView':
                list_answer = 'There is my stack list:\n'
                try:
                    if message.message.sender.username == self.admin:
                        for (index, d) in enumerate(self.stack_list):
                            list_answer += str(index + 1)
                            list_answer += ' ' + str(d['chat_id'])
                            list_answer += ' ' + d['chat_message']
                            list_answer += '\n'
                        list_answer = list_answer[:-1]
                        self.bot.send_message(chat.id, list_answer)
                    else:
                        raise Exception('You do not access for this function.')
                except Exception as ex_acc:
                    answer = ex_acc.args
                    self.bot.send_message(chat.id, answer)

            if re.match(r'[0-9]', text) and len(text) == 11:
                self.userID = text
                print(self.userID)

            if text == '/getJobs':
                if self.userID != 0:
                    print(self.userID)
                    response = requests.get(
                        'https://test.periodix.net/get-jobs.php?id=' +
                        self.userID).json()
                    print(response['JobTitle'])
                    bot_answer = 'There is your job: \n' + (
                        response['JobTitle'])
                    try:
                        self.bot.send_message(chat.id, bot_answer)
                    except Exception:
                        self.bot.send_message(chat.id, 'Unknow error. Sorry.')

            if digest_tag in text:
                try:
                    text = text.replace(digest_tag, '')
                    text = text.strip()
                    struct = {'chat_id': chat.id, 'chat_message': text}
                    self.stack_list.append(struct.copy())
                    self.bot.send_message(
                        chat.id,
                        'Done. I append your digest-message in my stack list.')
                except Exception:
                    self.bot.send_message(chat.id, 'There is error. Sorry.')
        except Exception:
            pass

    def run(self):
        print('Main loop started')
        while True:
            updates = self.bot.get_updates(offset=self.last_update_id).wait()
            try:
                for update in updates:
                    if int(update.update_id) > int(self.last_update_id):
                        self.last_update_id = update.update_id
                        self.process_message(update)
            except Exception as ex:
                print(traceback.format_exc())
Exemple #8
0
class DigestBot(object):
    token = '146027849:AAGY5g94uLZRfURyEZrkOuh5Kvn23GnFZC4' #Super secret bot token
    stack_list = []
    admin = 'Pablozzz'                                      #admin name
 
    def __init__(self):
        self.bot = TelegramBot(self.token)
        self.bot.get_me()
        last_updates = self.bot.get_updates(offset=0).wait()
        try:
            self.last_update_id = list(last_updates)[-1].update_id
        except IndexError:
            self.last_update_id = None
        print('last update id: {0}'.format(self.last_update_id))
 
    def process_message(self, message):                     #function for chech messages and send answers
        text = message.message.text
        chat = message.message.chat
        text = text.strip()
        bot_name = "zaurtox_bot"
                                                            #Substrings in messages = commands
        Toxa = "/Toxa"
        Zaur = "/Zaur"
        News = "/News"
        Help = "/Help"
        Valuta = "/Valuta"
        Start = "/Start"
        Slogan = "/Pogovorka"
        Leha = "/Leha"
        Igor = "/Igor"
        Pasha = "/Pasha"
        Photo = "/Photo"
        Sticker = "/Sticker"
        Bash = "/Bash"
                                                        #logger : print susbstr if catch that in message
        print('Got message: \33[0;32m{0}\33[0m from chat: {1}'.format(text, chat))


        try:
                                                            # commands
            #Help : print all supported commands
            if Help  in text:
                bot_answer = 'Команды /Help /News /Zaur /Toxa /Valuta /Pogovorka /Photo /Sticker /Bash\n'
                try:
                    self.bot.send_message(chat.id, bot_answer)
                except Exception:
                    self.bot.send_message(chat.id, 'Unknow error. Sorry.')
            #Start command it's nessesary for telegramm rules complete
            if Start  in text:
                bot_answer = 'Это эмоциональный бот, который может помочь с новостями и комментариями к ним /Help  \n'
                try:
                    self.bot.send_message(chat.id, bot_answer)
                except Exception:
                    self.bot.send_message(chat.id, 'Unknow error. Sorry.')
            #News parse news from rbc.ru rss and send in chat
            if News in text:
                d = feedparser.parse('http://static.feed.rbc.ru/rbc/internal/rss.rbc.ru/rbc.ru/news.rss')
                bot_answer =d['entries'][0]['title']+" "+d.entries[0]['link']
                try:
                    self.bot.send_message(chat.id, bot_answer)
                except Exception:
                    self.bot.send_message(chat.id, 'Unknow error. Sorry.')
            #Parse currenty rate and send in chat
            if Valuta in text:
                speaker=["Как заявил Антон Силуанов",
                         "Как заявил Алексей Улюкаев",
                         "Как заявила Эльвира Набиулина"]
                i = random.randrange(0,3,1)
                sentense = speaker[i] +", обоснованным курсом рубля явлеется: "
                HOST = "www.sberometer.ru"
                PORT = 80
                conn = http.client.HTTPConnection(HOST, PORT)
                conn.request("GET", "/")
                res = conn.getresponse()
                data = res.read()
                conn.close()
                answer = str(data)
                pos = answer.find("cursNow")
                bot_answer= sentense + answer[(pos+11):(pos+34):1]
                try:
                    self.bot.send_message(chat.id, bot_answer)
                except Exception:
                    self.bot.send_message(chat.id, 'Unknow error. Sorry.')
            #Parse strory from bach.org rss and print in chat
            if Bash in text:
                d = feedparser.parse('http://bash.im/rss/')
                bot_answer =d['entries'][0]['title']+" "+d.entries[0]['link']
                try:
                    self.bot.send_message(chat.id, bot_answer)
                except Exception:
                    self.bot.send_message(chat.id, 'Unknow error. Sorry.')
            #Select random slogan from file "pogovorki.txt" and send in chat
            if Slogan in text:
                fp = open("pogovorki.txt")
                lines = fp.readlines()
                fp.close()
                phrase = ["Как говорил мой дед: ",
                          "Как говорят у нас в народе: ",
                          "Народная мудрость: ",
                          "Как мы все знаем: "]
                a = random.randrange(0,4,1)
                i = random.randrange(0,1353,1)
                slogan = (lines[i].strip())
                bot_answer = phrase[a] + slogan
                try:
                    self.bot.send_message(chat.id, bot_answer)
                except Exception:
                    self.bot.send_message(chat.id, 'Unknow error. Sorry.')
            #Send strickers in chat
            if (text == Sticker):
                stikers = ["BQADAgADeAcAAlOx9wOjY2jpAAHq9DUC"]
                try:
                    self.bot.send_sticker(chat.id, stikers[0])
                except Exception:
                    self.bot.send_photo(chat.id, 'Unknow error. Sorry.')
            #Send photo from /photo path
            if (text == Photo):
                photos = ["photo/photo1.jpg"]
                          #"photo/photo2.jpg",
                          #"photo/photo3.jpg"]
                #i = random.randrange(0,3,1)
                fp = open(photos[0], "rb")
                file_info = InputFileInfo(photos[0], fp, 'image/jpg')
                a = InputFile('photo', file_info)
                self.bot.send_photo(chat.id, a)
                fp.close()
            #Send comment from Toxa.txt file
            if Toxa in text:
                fp = open("Toxa.txt")
                lines = fp.readlines()
                fp.close()
                i = random.randrange(0,len(lines)-1,1)
                slogan = (lines[i].strip())
                bot_answer = slogan + '\n'
                try:
                    self.bot.send_message(chat.id, bot_answer)
                except Exception:
                    self.bot.send_message(chat.id, 'Unknow error. Sorry.')
            #Send comment from Zaur.txt file
            if Zaur in text:
                fp = open("Zaur.txt")
                lines = fp.readlines()
                fp.close()
                i = random.randrange(0,len(lines)-1,1)
                slogan = (lines[i].strip())
                bot_answer = slogan + '\n'
                try:
                    self.bot.send_message(chat.id, bot_answer)
                except Exception:
                    self.bot.send_message(chat.id, 'Unknow error. Sorry.')
           #Send comment from Leha.txt file
            if Leha in text:
                fp = open("Leha.txt")
                lines = fp.readlines()
                fp.close()
                i = random.randrange(0,len(lines)-1,1)
                slogan = (lines[i].strip())
                bot_answer = slogan + '\n'
                try:
                    self.bot.send_message(chat.id, bot_answer)
                except Exception:
                    self.bot.send_message(chat.id, 'Unknow error. Sorry.')
           #Send comment from Igor.txt file
            if Igor in text:
                fp = open("igor.txt")
                lines = fp.readlines()
                fp.close()
                i = random.randrange(0,len(lines)-1,1)
                slogan = (lines[i].strip())
                bot_answer = slogan + '\n'
                try:
                    self.bot.send_message(chat.id, bot_answer)
                except Exception:
                    self.bot.send_message(chat.id, 'Unknow error. Sorry.')
           #Send comment from Pasha.txt file
            if Pasha in text:
                fp = open("pasha.txt")
                lines = fp.readlines()
                fp.close()
                i = random.randrange(0,len(lines)-1,1)
                slogan = (lines[i].strip())
                bot_answer = slogan + '\n'
                try:
                    self.bot.send_message(chat.id, bot_answer)
                except Exception:
                    self.bot.send_message(chat.id, 'Unknow error. Sorry.')
        except Exception:
            pass
 
    def run(self):
        print('Main loop started')
        while True:
            updates = self.bot.get_updates(offset=self.last_update_id).wait() #update status
            try:
                for update in updates:
                    if int(update.update_id) > int(self.last_update_id):
                        self.last_update_id = update.update_id
                        self.process_message(update)
            except Exception as ex:
                print(traceback.format_exc())
class BullsAndCowsNumbersBot(object):
    token = config.token
    
    def __init__(self):
        self.bot = TelegramBot(self.token)
        self.bot.get_me()
        last_updates = self.bot.get_updates(offset=0).wait()
        try:
            self.last_update_id = list(last_updates)[-1].update_id
        except IndexError:
            self.last_update_id = None
        print('last update id: {0}'.format(self.last_update_id))

    def check_user_answer(self, text):
        nums = '0123456789'
        if len(text)!=4:
            return False
        else:
            if not(text[0] in nums) or not(text[1] in nums) or not(text[2] in nums) or not(text[3] in nums):
                return False
            else:
                return True
                
    def answer_for_attempt(self, number_for_solve, number_attempt):
        indexes_in_number_for_solve = [0, 1, 2, 3]
        indexes_in_number_attempt = [0, 1, 2, 3]
        number_of_bulls = 0
        number_of_cows = 0
        # посчитаем количество быков
        i = 0
        while i < 4:
            if number_for_solve[i] == number_attempt[i]:
                number_of_bulls = number_of_bulls + 1
                indexes_in_number_for_solve.remove(i)
                indexes_in_number_attempt.remove(i)
            i = i + 1
        # посчитаем количество коров
        i = 0
        while i < 4:
            if i in indexes_in_number_attempt:
                for j in indexes_in_number_for_solve:
                    if number_for_solve[j] == number_attempt[i]:
                        number_of_cows = number_of_cows + 1
                        indexes_in_number_for_solve.remove(j)
                        break
            i = i + 1
        return {'number_of_bulls': number_of_bulls, 'number_of_cows': number_of_cows}

    def check_is_repeat(self, list_of_attempts, text):
        for element in list_of_attempts:
            if element[0] == text:
                return True
        return False

    def process_message(self, message):
        text = message.message.text
        chat = message.message.chat
        text = text.strip()

        print('{2} Got message: \33[0;32m{0}\33[0m from chat: {1}'.format(text, chat, strftime("%Y-%m-%d %H:%M:%S", gmtime())))

        try:
            if text == '/start':
                bot_answer = 'Это игра "Быки и коровы"\nИгра состоит в том, что я загадал число, а вам нужно его отгадать за меньшее число попыток.\n\
Чтобы прочитать правила воспользуйтесь командой /help\nИтак, я загадал число. Угадывайте'
                try:
                    result = mariadb_connector.read_current_game_state(chat.id)
                    num1 = str(random.randint(0, 9))
                    num2 = str(random.randint(0, 9))
                    num3 = str(random.randint(0, 9))
                    num4 = str(random.randint(0, 9))
                    number_for_solve = ''.join([num1, num2, num3, num4])
                    if (result == None):
                        mariadb_connector.write_new_user(chat.id, number_for_solve)
                    else:
                        mariadb_connector.write_current_game_state(chat.id, number_for_solve, None)
                    self.bot.send_message(chat.id, bot_answer)
                except Exception:
                    self.bot.send_message(chat.id, 'Unknow error. Sorry.')
            elif text == '/help':
                bot_answer = 'Это игра "Быки и Коровы"\n\
Я загадываю число из 4 цифр. Цифры могут повторяться, число может начинаться с нуля, т.е. я могу загадать даже такое число: 0103.\n\
Вам нужно отгадать число. Чем меньше попыток - тем лучше.\nДля того чтобы сделать попытку, просто напечатайте в ответ 4 цифры, например: 1234.\n\
После каждой вашей попытки я даю подсказку: количество быков и коров в вашем числе.\n\
Бык - это цифра, которая присутствует в загаданном числе и стоит на своем месте.\n\
Корова - это цифра, которая пристуствует в загаданном числе но стоит на другом месте.\n\
Т.е. например я загадал число 1234, вы отвечаете 1458: 1Б 1К (1 бык и 1 корова).\n\
Цифра 1 в вашем ответе это бык, т.к. в загаданном числе на первом месте тоже 1.\n \
Цифра 4 в вашем ответе это корова, т.к. в загаданном числе она есть, но должна стоять на четвертом месте.\n \
Цифры 5 и 8 в вашем ответе животными не являются, т.к. отсутствуют в загаданном числе.\n \
Чтобы прочитать более подробное объяснение как считаются быки и коровы, с пояснением сложных примеров, воспользуйтесь командой /rules'
                try:
                    self.bot.send_message(chat.id, bot_answer)
                except Exception:
                    self.bot.send_message(chat.id, 'Unknow error. Sorry.')
            elif text == '/rules':
                bot_answer = 'Подробнее о том как определется число быков и коров.\n\
Пример: загадано 0250, ваш ответ 0202.\n\
1) Считаем количество быков, для этого смотрим цифры вашего ответа по порядку.\n\
-первая цифра 0 - бык, т.к. в 0250 на первом месте тоже 0\n\
-вторая цифра 2 - бык, т.к. в 0250 на втором месте тоже 2\n\
-третья цифра 0 - не бык, т.к. в 0250 на третьем месте 5\n\
-четвертая цифра 2 - не бык, т.к. в 0250 на четвертом месте 0\n\
Итого 2 быка. 2Б\n\
2) Считаем количество коров, для этого смотрим цифры вашего ответа по порядку,\n\
но только те которые не являются быками:\n\
-первая цифра 0 - уже бык, поэтому не может быть коровой, хотя в загаданном числе она есть еще и на третьем месте\n\
-вторая цифра 2 - уже бык, не может быть коровой\n\
-третья цифра 0 - корова, т.к. не бык и при этом есть в 0250 на четвертом месте\n\
-четвертая цифра 2 - не бык и не корова. Она присутствует в 0250, но первые две цифры уже заняты быками, т.е. мы проверяем есть ли 2 среди последних цифр __50.\n\
иными словами каждая цифра в загаданном числе и в ответе может соответствовать только одному животному.\n\
Итого 1 корова. 1К\n\
Ответ будет 0202 2Б 1К\n\
Ещё примеры:\n\
1) загадано 1111 ответ 1214 - 2Б 0К\n\
2) загадано 2342 ответ 3222 - 1Б 2К\n\
3) загадано 5678 ответ 6587 - 0Б 4К\n\
4) загадано 1234 ответ 1111 - 1Б 0К'
                try:
                    self.bot.send_message(chat.id, bot_answer)
                except Exception:
                    self.bot.send_message(chat.id, 'Unknow error. Sorry.')
            elif text == '/newgame':
                bot_answer = 'В прошлой игре было загадано число: {}\nСыграем ещё? Я загадал новое число\nУгадывайте.'
                try:
                    result = mariadb_connector.read_current_game_state(chat.id)
                    num1 = str(random.randint(0, 9))
                    num2 = str(random.randint(0, 9))
                    num3 = str(random.randint(0, 9))
                    num4 = str(random.randint(0, 9))
                    number_for_solve = ''.join([num1, num2, num3, num4])
                    if (result == None):
                        mariadb_connector.write_new_user(chat.id, number_for_solve)
                        self.bot.send_message(chat.id, bot_answer.format('...'))
                    else:
                        mariadb_connector.write_current_game_state(chat.id, number_for_solve, None)
                        self.bot.send_message(chat.id, bot_answer.format(result['number_for_solve']))
                except Exception:
                    self.bot.send_message(chat.id, 'Unknow error. Sorry.')
            else:
                try:
                    start_new_game = False
                    if self.check_user_answer(text):
                        result = mariadb_connector.read_current_game_state(chat.id)
                        if result == None:
                            num1 = str(random.randint(0, 9))
                            num2 = str(random.randint(0, 9))
                            num3 = str(random.randint(0, 9))
                            num4 = str(random.randint(0, 9))
                            number_for_solve = ''.join([num1, num2, num3, num4])
                            mariadb_connector.write_new_user(chat.id, number_for_solve)
                            result = mariadb_connector.read_current_game_state(chat.id)
                        bulls_and_cows = self.answer_for_attempt(result['number_for_solve'], text)
                        if bulls_and_cows['number_of_bulls'] == 4:
                            start_new_game = True
                        if result['current_game'] == None:
                            result['current_game'] = [[text, str(bulls_and_cows['number_of_bulls']), str(bulls_and_cows['number_of_cows'])]]
                            mariadb_connector.write_current_game_state(chat.id, result['number_for_solve'], result['current_game'])
                            bot_answer = ''
                            for attempt in result['current_game']:
                                bot_answer = bot_answer + attempt[0] + '  ' + str(attempt[1]) + 'Б ' + str(attempt[2]) + 'К\n'
                        else:
                            if self.check_is_repeat(result['current_game'], text):
                                bot_answer = 'Вы уже писали число {}'.format(text)
                            else:
                                result['current_game'].append([text, str(bulls_and_cows['number_of_bulls']), str(bulls_and_cows['number_of_cows'])])
                                mariadb_connector.write_current_game_state(chat.id, result['number_for_solve'], result['current_game'])
                                bot_answer = ''
                                for attempt in result['current_game']:
                                    bot_answer = bot_answer + attempt[0] + '  ' + str(attempt[1]) + 'Б ' + str(attempt[2]) + 'К\n'
                        if bulls_and_cows['number_of_bulls'] == 4:
                            if result['current_game'] == None:
                                mariadb_connector.write_statistics(chat.id, True, 0)
                            else:
                                mariadb_connector.write_statistics(chat.id, True, len(result['current_game']))
                        else:
                            if result['current_game'] == None:
                                mariadb_connector.write_statistics(chat.id, False, 0)
                            else:
                                mariadb_connector.write_statistics(chat.id, False, len(result['current_game']))
                    else:
                        bot_answer = "Ошибка при обработке ответа. В вашем ответе должны быть четыре цифры. Число может начинаться с нуля, цифры могут повторяться, например: 0373. Если хотите прочитать о правилах игры подробно, воспользуйтесь командой /help"
                    if start_new_game:
                        bot_answer_victory = 'Вы угадали! Это было число: {}\nСыграем ещё? Я загадал новое число\nУгадывайте.'.format(text)
                        try:
                            num1 = str(random.randint(0, 9))
                            num2 = str(random.randint(0, 9))
                            num3 = str(random.randint(0, 9))
                            num4 = str(random.randint(0, 9))
                            number_for_solve = ''.join([num1, num2, num3, num4])
                            mariadb_connector.write_current_game_state(chat.id, number_for_solve, None)
                            bot_answer = bot_answer + '\n' + bot_answer_victory
                        except Exception:
                            self.bot.send_message(chat.id, 'Unknow error. Sorry.')
                    self.bot.send_message(chat.id, bot_answer)
                except Exception:
                    self.bot.send_message(chat.id, 'Unknow error. Sorry.')
        except Exception:
            pass
 
    def run(self):
        print('Main loop started')
        while True:
            updates = self.bot.get_updates(offset=self.last_update_id).wait()
            try:
                for update in updates:
                    if int(update.update_id) > int(self.last_update_id):
                        self.last_update_id = update.update_id
                        self.process_message(update)
            except Exception as ex:
                print(traceback.format_exc())