class TelegramBot(object): def __init__(self, chat_id=None): from telegram.bot import Bot telegram_creds = settings().creds['telegram'] token = telegram_creds['token'] if chat_id is not None: self._chat_id = chat_id else: self._chat_id = telegram_creds.get('chat') self.bot = Bot(token=token) @property def chat_id(self): if self._chat_id is None: chat = self.bot.getUpdates(limit=1)[0].message.chat logger.debug("Imprinted chat id %d of type %s", chat.id, chat.type) self._chat_id = chat.id return self._chat_id def post(self, report, **kwargs): message = self.bot.send_message( self.chat_id, report, parse_mode='Markdown', ) return message __call__ = post
class TelegramBot: def __init__(self, bot_token, bot_name): self.bot_token = bot_token self.bot_name = bot_name self.on_message = None self.handler = None self.bot = Bot(token=bot_token) self.thread = BotRunnerThread(self.bot, self.on_update) def start(self): self.thread.start() def send(self, chat_id, message): self.bot.send_message(chat_id=chat_id, text=message) def on_update(self, update): logging.info("Update: {}".format(update)) if self.handler is None: return self.handler.on_new_message(update) def on_exception(self, exception): logging.error(repr(exception))
def handle(self, bot: Bot, update: Update, user_data, chat_data): data = json.loads(update.callback_query.data) moderator = ... if Moderator.select().where(Moderator.user_id == update.callback_query. from_user.id).exists(): moderator = Moderator.select().where( Moderator.user_id == update.callback_query.from_user.id).peek( 1) else: moderator = Moderator( user_id=update.callback_query.from_user.id, username=update.callback_query.from_user.username or update.callback_query.from_user.first_name) moderator.save() if Vote.select().where( Vote.moderator == moderator, Vote.publication_id == data.get('publication_id'), Vote.points > 0).exists(): bot.answer_callback_query( callback_query_id=update.callback_query.id, text='Вы уже голосовали', show_alert=False) else: vote = Vote( publication_id=data.get('publication_id'), moderator=moderator, date=datetime.datetime.now(), points=data.get('points'), ) vote.save() bot.answer_callback_query( callback_query_id=update.callback_query.id, text='Ваш голос принят', show_alert=False)
def admin_menu(bot: Bot, update: Update) -> None: bot.send_message( update.effective_chat.id, BOT_ADMIN_MENU, reply_markup=ReplyKeyboardMarkup(menu, one_time_keyboard=True, resize_keyboard=True))
def start(bot: Bot, update: Update): if update.message.chat.type != Chat.PRIVATE: bot.send_message(update.message.chat_id, "unsupported") return bot.send_message(update.message.chat_id, WELCOME_MSG, reply_markup=ReplyKeyboardMarkup([[ KeyboardButton(RULES_CMD), KeyboardButton(MATCH_LIST_CMD), KeyboardButton(PISHBINI_CMD) ]])) user_temp_data[update.message.from_user.id] = { 'status': STATUS_IDLE, 'temp_data': None } u, created = User.objects.get_or_create( first_name=update.message.from_user.first_name, id=update.message.from_user.id) if update.message.from_user.last_name: u.last_name = update.message.from_user.last_name if update.message.from_user.username: u.username = update.message.from_user.username u.save()
def send_msg(msg: str, user_id: str, bot: Bot = None, parse_mode: ParseMode = ParseMode.MARKDOWN) -> None: """ Sends a message to the given user or chat_id """ logger.debug('Sending telegram message') bot = bot or UPDATER.bot try: try: bot.send_message( user_id, text=msg, parse_mode=parse_mode, ) except NetworkError as network_err: # Sometimes the telegram server resets the current connection, # if this is the case we send the message again. logger.warning('Telegram NetworkError: %s! Trying one more time.', network_err.message) bot.send_message( user_id, text=msg, parse_mode=parse_mode, ) except TelegramError as telegram_err: logger.warning('TelegramError: %s! Giving up on that message.', telegram_err.message)
def doAct(self, bot: Bot, chat, message): text_message = GetTextFromMessage(message) save_text = self.data.format(text_message=text_message, data=chat.data) if self.eval: try: data = chat.data eval_result = eval( save_text ) # very risky move , can be hacked in a second , suck as "()"*8**5 # [i for i in range(10**100)] crashes the app chat.data[self.data_name] = eval_result except: print("eval '{}' cannot be evaluated chat_id={} ".format( save_text, chat.id)) bot.sendMessage( chat_id=chat.id, text="eval '{}' cannot be evaluated".format(save_text), reply_to_message_id=message.message_id) return else: chat.data[self.data_name] = save_text print( "data has been changed ,,, chat_id - {} , data_name - {} , value={}" .format(chat.id, self.data_name, chat.data[self.data_name])) return super(SaveCommand, self).doAct(bot, chat, message)
def doAct(self, bot: Bot, chat, message): format_names = GetFormatNames(self.data) print('found formant_name ') print(format_names) print("chat.data") print(chat.data) for name in format_names: if not Object.hasAttrNested(chat, name): print( "error - trying to find {format_name} in chat.data but not found , chat_id={chat_id}" .format(format_name=name.split('.', 1)[1], chat_id=chat.id)) bot.sendMessage( chat_id=chat.id, text='error - {} not found in Chat'.format(name), reply_to_message_id=message.message_id) return text = self.data.format(data=chat.data, bot_user_name=bot_user_name) if text == "": print("error - act id {} tried sending a null text".format( self.id)) return bot.sendMessage(chat_id=chat.id, text=text, reply_to_message_id=message.message_id, reply_markup=self.markup) return super(TextResponse, self).doAct(bot, chat, message)
def set_default_service_callback(bot: Bot, update: Update): msg = set_default_service_tpl() buttons = services_buttons(lambda svc: "set_default %s" % svc.name) bot.send_message(chat_id=update.message.chat_id, text=msg, parse_mode=ParseMode.HTML, reply_markup=buttons)
def setcommands(self, update, context) -> None: command = [ BotCommand("controlpanel", "show command buttons"), BotCommand("cleandata", "clean JSON data files"), BotCommand("addexception", "add pair to scanner exception list"), BotCommand("removeexception", "remove pair from scanner exception list"), BotCommand("startscanner", "start auto scan high volume markets and start bots"), BotCommand("stopscanner", "stop auto scan high volume markets"), BotCommand("addnew", "add and start a new bot"), BotCommand("deletebot", "delete bot from startbot list"), BotCommand("margins", "show margins for all open trades"), BotCommand("trades", "show closed trades"), BotCommand("stats", "show exchange stats for market/pair"), BotCommand("help", "show help text") # BotCommand("showinfo", "show all running bots status"), # BotCommand("showconfig", "show config for selected exchange"), # BotCommand("startbots", "start all or selected bot"), # BotCommand("stopbots", "stop all or the selected bot"), # BotCommand("pausebots", "pause all or selected bot"), # BotCommand("resumebots", "resume paused bots"), # BotCommand("buy", "manual buy"), # BotCommand("sell", "manual sell"), ] ubot = Bot(self.token) ubot.set_my_commands(command) update.message.reply_text( "<i>Bot Commands Created</i>", parse_mode="HTML", reply_markup=ReplyKeyboardRemove(), )
def add_user(bot: Bot, update: Update, user_data: dict) -> (int, str): uid = update.message.from_user.id message = update.message.text username = update.message.from_user.username if is_cancelled(message): user_data['reply_markup'] = ReplyKeyboardMarkup( REGISTER_KEYBOARD, True) send_cancel(bot, uid, user_data) return ConversationHandler.END elif is_stopped(message): on_stop(message), return ConversationHandler.END user = Users.create(telegram_id=uid, username=username) user.set_city(user_data['reg_city']) user.set_email(user_data['reg_email']) user.set_status(user_data['reg_email']) user.save() # TODO: check email is valid for key, val in user_data.items(): del key, val thread = Thread(name=f"get_and_save::{uid}, {user.email}", target=get_and_save, args=((user.email, user.is_student, uid), )) thread.start() bot.send_message(uid, MESSAGES['add_user:msg'], ParseMode.HTML, reply_markup=ReplyKeyboardMarkup(START_KEYBOARD, True)) return ConversationHandler.END
def set_default(bot: Bot, update: Update): name = update.callback_query.data.split(" ").pop() db.default_service = name msg = set_default_service_success_tpl() bot.send_message(chat_id=update.callback_query.message.chat.id, text=msg, parse_mode=ParseMode.HTML)
def show_about(bot: Bot, update: Update) -> str: bot.send_message( update.message.chat.id, MESSAGES['show_about'], ParseMode.HTML ) return SETTINGS
def __init__(self, bot_id=None, bot_token=None, chat_id=None, message_handler={}, expire_time=60, expired_handler=None): if bot_token is None: logger.debug("Telegram Bot Disabled.") self.enabled = True return if bot_id is None or bot_id == "": self.bot_id = str( random.randint(random.randint(1, 99), random.randint(100, 9999))) else: self.bot_id = bot_id logger.debug("Telegram Bot ID. %s", self.bot_id) self.bot_token = bot_token self._bot = Bot(bot_token) self.chat_id = chat_id self.message_handler = message_handler if expired_handler is not None: self.question_tmp = expiredict(expired_handler) else: self.question_tmp = expiredict( expire_time=expire_time, expired_callback=self.expired_question) self.enabled = False
def send_current(bot: Bot, uid: int, email: str=None, city: str=None) -> None: bot.send_message( uid, MESSAGES['current'].format(email, city), ParseMode.HTML, reply_markup=ReplyKeyboardMarkup(SETTINGS_KEYBOARD, True) )
def start(self, bot: Bot, update: Update) -> None: if update.message.chat_id not in parse_list( config["CHATS"]["main_chats"]): from_id = update.message.from_user.id from_username = update.message.from_user.username name = f"user:{from_id}" if from_username is not None: rdb.hsetnx(name, "username", from_username) if rdb.hget(name, "allowed") == "true": update.message.reply_text(config["STRINGS"]["user_took_quiz"]) else: keyboard = [[InlineKeyboardButton( config["STRINGS"]["ready"], callback_data="ready")]] reply_markup = InlineKeyboardMarkup(keyboard) update.message.reply_text( config["STRINGS"]["start_message"].format( username=from_username or "fellow pythonist", start=config["COMMANDS"]["start"], correct_answers=config["GENERAL"]["correct_answers"], questions_count=config["GENERAL"]["questions_count"]), parse_mode="Markdown", reply_markup=reply_markup) else: if config["GENERAL"]["send_start_no"] == "true": update.message.reply_text(config["STRINGS"]["no"]) if config["GENERAL"]["delete_commands"] == "true": bot.delete_message(chat_id=update.message.chat.id, message_id=update.message.message_id)
def remove(self, bot: Bot, update: Update) -> None: if is_admin(bot, update, update.message.from_user.id): pass else: if config["GENERAL"]["delete_commands"] == "true": bot.delete_message(chat_id=update.message.chat.id, message_id=update.message.message_id)
def check_answer(self, bot: Bot, update: Update) -> None: user_id: int = self.query.from_user.id name: str = f"user:questions:{user_id}" name_results: str = f"user:results:{user_id}" answer_data = parse_list(self.query.data, splitter=":") print(answer_data) chosen = rdb.hget( name=name_results, key=answer_data[1]).decode("utf-8") if chosen != "u": bot.answerCallbackQuery( callback_query_id=self.query.id, text=config["STRINGS"]["already_chosen"], show_alert=True) return else: user_questions = json.loads(rdb.get(name)) current_question = user_questions[answer_data[1]] choice_string = "c" if int(current_question["answer"]) \ == answer_data[2] else "w" print(choice_string) print(current_question) rdb.hset( name=name_results, key=answer_data[1], value=choice_string) self.make_keyboard(bot, update)
def __init__(self, bot_token, bot_name): self.bot_token = bot_token self.bot_name = bot_name self.on_message = None self.handler = None self.bot = Bot(token=bot_token) self.thread = BotRunnerThread(self.bot, self.on_update)
def change_chats_page(bot: Bot, update: Update) -> None: query = update.callback_query print(query.data) page = int(query.data.split('_')[1]) bot.edit_message_reply_markup( chat_id=update.callback_query.message.chat_id, message_id=update.callback_query.message.message_id, reply_markup=InlineKeyboardMarkup(get_chats_keyboard(page)))
def send(bot=None): if not bot: bot = Bot(TELEGRAM["token"]) bot.edit_message_text(chat_id=TELEGRAM["chat_id"], message_id=TELEGRAM["msg_id"], text=parse_message(), parse_mode=ParseMode.MARKDOWN, timeout=60) # , reply_markup=get_keyboard())
def __init__(self, token): self.token = token self.bot = Bot(token) self.updater = Updater(token, use_context=True) self.opentdb_client = OpenTdbClient() self.db = DB.instance() self.dispatcher = self.updater.dispatcher self.setup_handlers()
def __init__(self, name, token="512720388:AAHjYnJvvNld3rb70J1vp40gDEiRdcPHxsE", chat_id="-262107883"): self.direct = Bot(token=token) self.chat_id = chat_id self.name = name self.start_time = time.time()
def on_back(bot: Bot, update: Update) -> int: bot.send_message( update.message.from_user.id, MESSAGES['on_back:msg'], ParseMode.HTML, reply_markup=ReplyKeyboardMarkup(START_KEYBOARD, True) ) return ConversationHandler.END
def __init__(self, chat_id=None): from telegram.bot import Bot telegram_creds = settings().creds['telegram'] token = telegram_creds['token'] if chat_id is not None: self._chat_id = chat_id else: self._chat_id = telegram_creds.get('chat') self.bot = Bot(token=token)
def is_message(message: object): chat_id = message["from"]["id"] text = message["text"] if text == command_start: users_dict[chat_id] = Bot(TOKEN, chat_id) if chat_id in users_dict: users_dict[chat_id].last_message_id = None users_dict[chat_id].handle_input(text=text)
def inline_search(bot: Bot, update: Update): query = update.inline_query.query if not query: return results = scryfall.cards_search(query) if results: items = parse.cards_to_articles(results)[1:50] bot.answer_inline_query(update.inline_query.id, items)
def _handle_show_command(bot: Bot, update: Update): response = '\n'.join([ '`{k}` {v}'.format(k='{:>7}'.format(k), v=v) for k, v in tencodes_dictionary.items() ]) message: Message = update.message bot.send_message(chat_id=message.chat_id, text=response, parse_mode=ParseMode.MARKDOWN)
def __init__(self, auth_token): # Create the Updater and pass it your bot's token. # Make sure to set use_context=True to use the new context based callbacks # Post version 12 this will no longer be necessary self.db_manager = DB_Manager(check_same_thread=False) self.updater = Updater(auth_token, use_context=True) self.bot = Bot(auth_token) self.logger = Logger("telegram.log") self.logger.info("Starting the daemon...")
def send(bot=None, full=False, force=False): with open("{}/{}".format(os.path.dirname(os.path.realpath(__file__)), 'view.json'), "r") as read_file: data = json.load(read_file) if not force and data and datetime.strptime(data[0][:19], '%Y-%m-%dT%H:%M:%S') > datetime.utcnow() - timedelta( minutes=3): full = True if not bot: bot = Bot(TELEGRAM["token"]) bot.edit_message_text(chat_id=TELEGRAM["chat_id"], message_id=TELEGRAM["msg_id"], parse_mode=ParseMode.MARKDOWN, text=more() if full else less(), reply_markup=get_keyboard(full))
def handle_notification(sender, instance, created, **kwargs): if created: bot = Bot(token=settings.TELEGRAM_TOKEN) users = Contact.objects.filter(subscribed_notifications__icontains=instance.notification_type) if len(users) > 0: for user in users: bot.send_message(chat_id=user.chat_id, text=instance.message) instance.delivered = True instance.save()