class TgBot: def __init__(self, events): self.bot = TeleBot(config_secrets.tg_bot_key) self.events = events def listener(self, messages): for mes in messages: self.events.append({ "text": mes.text, "first": mes.from_user.first_name, "last": mes.from_user.last_name, "id": str(mes.from_user.id), "platform": "tg" }) def main_loop(self): self.bot.set_update_listener(self.listener) self.bot.polling() @staticmethod def parse_row(row): # mark_by_type = ["", "(ничье)", "(синие)", "(красное)", "(бомба!)"] mark_by_type = ["⬜", "🟦", "🟥", "⬛"] # mark_by_type = ["", "нич", "син", "кра", "бом"] # open_by_type = ["", "открыто"] markup_row = [] for but in row: if type(but) == str: markup_row.append(tgButton(but.capitalize())) elif but[1]: markup_row.append(tgButton(f"{but[2].capitalize()}\n{mark_by_type[but[0]]}")) else: markup_row.append(tgButton(f"{but[2].upper()}")) return markup_row def write_message(self, player_id, text, buttons=None): markup = None if buttons is not None: markup = tgMarkup(row_width=5, resize_keyboard=True) for row in buttons: markup.add(*self.parse_row(row)) while True: try: self.bot.send_message(player_id, text, reply_markup=markup, parse_mode='markdown') break except Exception as ex: print(f"exception {ex}") sleep(1)
class TgBot(threading.Thread): def loadCommandConfig(self): pass def loadPersonConfig(self): persons = {} return persons def __init__(self, config, admins, tunnels, loopDelay=0.1, debug=False): super(TgBot, self).__init__() self.debug = debug self.stopped = Event() self.loopDelay = loopDelay self.admins = admins self.tunnels = tunnels self.config = config self.botUserName = config['botUserName'] self.bot = TeleBot(config['token']) self.commands = [ # AddAdmin(bot=self, cmd=['add-admin']), # Alarm('alarm', time.time()) Bind(bot=self, cmd=['b', 'bind']), ListBind(bot=self, cmd=['lb', 'listbind', 'list-bind']), Toggle(bot=self, cmd=['t', 'toggle']), ListToggle(bot=self, cmd=['lt', 'listtoggle', 'list-toggle']), UnBind(bot=self, cmd=['ub', 'unbind', 'un-bind']) ] self.persons = self.loadPersonConfig() def sendMessage(self, _id, _msg, parse_mode=None): self.bot.send_message(chat_id=_id, text=_msg, parse_mode=parse_mode) def replyTo(self, msg, _msg): self.bot.reply_to(msg, _msg) def listbind_handler(self, message): print(message) def handler(self, msg): for each in msg: try: _from = each.from_user _chat = each.chat if each.text and each.text.startswith('#'): _text = each.text for tunnel in getMatchTunnels(self.tunnels, tgId=_chat.id): if tunnel.tg['toggle']: name = _from.username or _from.first_name or _from.last_name message = '[Anonymous]: {0}'.format( _text[2:]) if _text.startswith( '##') else '[{0}]: {1}'.format( name, _text[1:]) tunnel.tk['queue'].put(message) if self.debug: print(each) except Exception as e: if self.debug: traceback.print_exc() def queueHandler(self): while not self.stopped.wait(self.loopDelay): for each in self.tunnels: tg = each.tg while not tg['queue'].empty() and tg['toggle']: chatId = tg['id'] msg = tg['queue'].get() try: if '<img' in msg: link = re.search('src=\".*?\"', msg).group(0)[5:-1] if '.gif' in msg: self.bot.send_document(chatId, link) else: self.bot.send_photo(chatId, link) elif '</' in msg: self.bot.send_message(chatId, msg, parse_mode='HTML') else: self.bot.send_message(chatId, msg, parse_mode='Markdown') except Exception as e: self.bot.send_message(chatId, msg) if self.debug: traceback.print_exc() def start(self): super(TgBot, self).start() for cmd in self.commands: cmd.register() self.bot.set_update_listener(self.handler) thread = threading.Thread(target=self.queueHandler) thread.start() def run(self): while not self.stopped.wait(self.loopDelay): try: self.bot.polling(none_stop=False) except: if self.debug: traceback.print_exc() def stop(self): self.bot.stop_bot() self.stopped.set()
def listener(messages): for m in messages: print(str(m)) log = { 'date': dt.datetime.fromtimestamp(m.date), 'text': m.json['text'], 'username': m.json['from']['username'], 'type': 'message' } db_collection.insert_one(log) print('inserted to mongo db') user = environ['MONGO_USERNAME'] password = environ['MONGO_PASSWORD'] database = environ['MONGO_DB_NAME'] connection_end = 'cluster0-shard-00-00-dbct0.mongodb.net:27017,cluster0-shard-00-01-dbct0.mongodb.net:27017,cluster0-shard-00-02-dbct0.mongodb.net:27017/test?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin&retryWrites=true' client = pymongo.MongoClient("mongodb://{0}:{1}@{2}".format( user, password, connection_end)) db = client[database] # change this to start another collection db_collection = db.testing pprint(client.list_database_names()) bot.set_update_listener(listener) bot.set_webhook("https://{0}.glitch.me/{1}".format(environ['PROJECT_NAME'], environ['TELEGRAM_TOKEN']))
markup = '' bot.send_message(chat_id, msg, reply_markup=markup, parse_mode='markdown', disable_web_page_preview=True) def printer(msgs): for message in msgs: print(message.chat.id, message.chat.username, message.chat.first_name,\ message.chat.last_name, message.text, message.content_type) control = Control() bot.set_update_listener(printer) bot.remove_webhook() def loging(text): with open('log.txt', 'a') as f: text = ctime() + '\n' + str(text) + '\n\n' f.write(text) for i in range(0, 20): try: loging('Запуск бота!') bot.polling(none_stop=True) except Exception as ex: loging(ex)
# Create your tasks here from __future__ import absolute_import, unicode_literals from celery import shared_task from telebot import TeleBot from .constants.strings import TOKEN bot = TeleBot(TOKEN, threaded=False) @shared_task def send_notification(chat_id, text): bot.send_message(chat_id, text, parse_mode='HTML') bot.set_update_listener(send_notification)
send_error(m.chat.id) def callback_listener(call): logger.info(call) try: message_dispatched = dispatch(bot, chats, call.from_user.id, call.data, call.message.message_id) if not message_dispatched: logging.warning(u'Message2 is not dispatched (chat id - {0}) | message: {1}'.format(call.from_user.id, call.data)) send_error(call.from_user.id) except Exception as e: if chats.get(call.from_user.id) is not None: del chats[call.from_user.id] logging.error(u'Error2 by chat with id {0} | error: {1}'.format(call.from_user.id, e)) send_error(call.from_user.id) if __name__ == '__main__': bot = TeleBot(config.token) bot.set_update_listener(listener) @bot.callback_query_handler(func=lambda call: True) def test_callback(call): callback_listener(call) bot.polling(none_stop=True) while True: time.sleep(200)
bot.send_message(chat_id=message.chat.id, text=text) @bot.callback_query_handler( func=lambda call: call.data in {'reset_y', 'reset_n'}) def reset_places(call): message = call.message if call.data == 'reset_y': bot.delete_message(chat_id=message.chat.id, message_id=message.message_id) storage.delete_places_for_user(message.chat.id) text = 'Все места успешно удалены.' elif call.data == 'reset_n': text = 'Удаление всех мест отменено.' bot.delete_message(chat_id=message.chat.id, message_id=message.message_id) bot.send_message(chat_id=message.chat.id, text=text) def handle_unsupported_command(messages): allowed_commands = ['/start', '/help', '/add', '/reset', '/list'] for message in messages: if message.text not in allowed_commands: bot.send_message(chat_id=message.chat.id, text='Данная команда не поддерживается.') bot.set_update_listener(handle_unsupported_command)