Python telegram.error.Unauthorized() Examples
The following are 30
code examples of telegram.error.Unauthorized().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
telegram.error
, or try the search function
.
Example #1
Source File: __main__.py From SkittBot with GNU General Public License v3.0 | 6 votes |
def donate(bot: Bot, update: Update): user = update.effective_message.from_user chat = update.effective_chat # type: Optional[Chat] if chat.type == "private": update.effective_message.reply_text(DONATE_STRING, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True) if OWNER_ID != 254318997 and DONATION_LINK: update.effective_message.reply_text("You can also donate to the person currently running me " "[here]({})".format(DONATION_LINK), parse_mode=ParseMode.MARKDOWN) else: try: bot.send_message(user.id, DONATE_STRING, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True) update.effective_message.reply_text("I've PM'ed you about donating to my creator!") except Unauthorized: update.effective_message.reply_text("Contact me in PM first to get donation information.")
Example #2
Source File: job.py From ultimate-poll-bot with MIT License | 6 votes |
def send_notifications_for_poll(context, session, poll, message_key): """Send the notifications for a single poll depending on the remaining time.""" locale = poll.locale for notification in poll.notifications: try: # Get the chat and send the notification tg_chat = context.bot.get_chat(notification.chat_id) tg_chat.send_message( i18n.t(message_key, locale=locale, name=poll.name), parse_mode="markdown", reply_to_message_id=notification.poll_message_id, ) except BadRequest as e: if e.message == "Chat not found": session.delete(notification) # Bot was removed from group except Unauthorized: session.delete(notification)
Example #3
Source File: bot.py From ab-2018 with GNU General Public License v3.0 | 6 votes |
def run_job_queue(bot): try: redix = redis.Redis(host=REDIS_HOST, port=REDIS_PORT) while True: # get job from redis _, job = redix.brpop(TELEGRAM_WORKER_QUEUE) job = json.loads(job) message = "Hello this is your periodic star reminder and these are the lucky repos:\n" for repo in job["repos"]: message = "{}\n--\t[{}]({})".format(message, repo["name"], repo["url"]) message = "{}".format(message) try: bot.send_message(int(job['to']), message, parse_mode="Markdown", disable_web_page_preview=True) except error.BadRequest as e: logger.error("{}, UserID: {}".format(e, job["to"])) except error.Unauthorized as e: logger.error("{}, UserID: {}".format(e, job["to"])) # report job done. except KeyboardInterrupt: raise KeyboardInterrupt
Example #4
Source File: common.py From NanoWalletBot with BSD 3-Clause "New" or "Revised" License | 6 votes |
def push_simple(bot, chat_id, message): try: bot.sendMessage(chat_id=chat_id, text=message) except BadRequest as e: bot.sendMessage(chat_id=chat_id, text=replace_unsafe(message)) except RetryAfter as e: sleep(240) bot.sendMessage(chat_id=chat_id, text=message) except TimedOut as e: sleep(60) bot.sendMessage(chat_id=chat_id, text=message) except Unauthorized as e: sleep(0.25) except NetworkError as e: sleep(30) bot.sendMessage(chat_id=chat_id, text=message) except Exception as e: sleep(1) bot.sendMessage(chat_id=chat_id, text=message)
Example #5
Source File: __main__.py From Marie-2.0-English with GNU General Public License v3.0 | 6 votes |
def donate(bot: Bot, update: Update): user = update.effective_message.from_user chat = update.effective_chat # type: Optional[Chat] if chat.type == "private": update.effective_message.reply_text(DONATE_STRING, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True) if OWNER_ID != 254318997 and DONATION_LINK: update.effective_message.reply_text("You can also donate to the person currently running me " "[here]({})".format(DONATION_LINK), parse_mode=ParseMode.MARKDOWN) else: try: bot.send_message(user.id, DONATE_STRING, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True) update.effective_message.reply_text("I've PM'ed you about donating to my creator!") except Unauthorized: update.effective_message.reply_text("Contact me in PM first to get donation information.")
Example #6
Source File: bot.py From TranscriberBot with GNU General Public License v3.0 | 6 votes |
def active_check(self, fn, *args, **kwargs): err = None res = None try: res = fn(*args, **kwargs) except Unauthorized as e: pprint.pprint(e) logger.error(e) err = e if err is not None: chat_id = kwargs['chat_id'] if chat_id not in self.active_chats_cache or self.active_chats_cache[chat_id] == 1: logger.debug("Marking chat {} as inactive".format(chat_id)) self.active_chats_cache[chat_id] = 0 TBDB.set_chat_active(chat_id, self.active_chats_cache[chat_id]) raise err return res
Example #7
Source File: maintenance.py From sticker-finder with MIT License | 6 votes |
def distribute_tasks(bot, session): """Distribute tasks under idle maintenance chats.""" idle_maintenance_chats = ( session.query(Chat) .filter(Chat.is_maintenance) .filter(Chat.current_task_id.is_(None)) .all() ) for chat in idle_maintenance_chats: try: tg_chat = call_tg_func(bot, "get_chat", args=[chat.id]) except BadRequest as e: if e.message == "Chat not found": # noqa session.delete(chat) continue raise e try: check_maintenance_chat(session, tg_chat, chat, job=True) except (Unauthorized, ChatMigrated): session.delete(chat) session.commit()
Example #8
Source File: bismillah.py From BismillahBot with GNU Affero General Public License v3.0 | 6 votes |
def main(): global update_id bot = telegram.Bot(token=TOKEN) try: update_id = bot.get_updates()[0].update_id except IndexError: update_id = None interface = telegram.ReplyKeyboardMarkup( [["Arabic", "Audio", "English", "Tafsir"], ["Previous", "Random", "Next"]], resize_keyboard=True) data = { "english": Quran("translation"), "tafsir": Quran("tafsir"), "index": make_index(), "interface": interface } data["default_query_results"] = get_default_query_results(data["english"]) while True: try: serve(bot, data) except NetworkError: sleep(1) except Unauthorized: # user has removed or blocked the bot update_id += 1 except TelegramError as e: if "Invalid server response" in str(e): sleep(3) else: raise e
Example #9
Source File: log_channel.py From EmiliaHikari with GNU General Public License v3.0 | 6 votes |
def loggable(func): @wraps(func) def log_action(update, context, *args, **kwargs): result = func(update, context, *args, **kwargs) chat = update.effective_chat # type: Optional[Chat] message = update.effective_message # type: Optional[Message] if result: if chat.type == chat.SUPERGROUP and chat.username: result += "\n<b>Link:</b> " \ "<a href=\"http://telegram.me/{}/{}\">klik disini</a>".format(chat.username, message.message_id) log_chat = sql.get_chat_log_channel(chat.id) if log_chat: try: send_log(context.bot, log_chat, chat.id, result) except Unauthorized: sql.stop_chat_logging(chat.id) elif result == "": pass else: LOGGER.warning("%s was set as loggable, but had no return statement.", func) return result return log_action
Example #10
Source File: __main__.py From EmiliaHikari with GNU General Public License v3.0 | 6 votes |
def donate(update, context): user = update.effective_message.from_user chat = update.effective_chat # type: Optional[Chat] if chat.type == "private": update.effective_message.reply_text(tl(update.effective_message, DONATE_STRING), parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True) if OWNER_ID != 388576209 and DONATION_LINK: update.effective_message.reply_text(tl(update.effective_message, "Anda juga dapat menyumbang kepada orang yang saat ini menjalankan saya " "[disini]({})").format(DONATION_LINK), parse_mode=ParseMode.MARKDOWN) else: try: context.bot.send_message(user.id, tl(update.effective_message, DONATE_STRING), parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True) update.effective_message.reply_text(tl(update.effective_message, "Saya sudah PM Anda tentang donasi untuk pencipta saya!")) except Unauthorized: update.effective_message.reply_text(tl(update.effective_message, "Hubungi saya di PM dulu untuk mendapatkan informasi donasi.")) # Avoid memory dead
Example #11
Source File: __main__.py From tgbot with GNU General Public License v3.0 | 6 votes |
def donate(bot: Bot, update: Update): user = update.effective_message.from_user chat = update.effective_chat # type: Optional[Chat] if chat.type == "private": update.effective_message.reply_text(DONATE_STRING, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True) if OWNER_ID != 254318997 and DONATION_LINK: update.effective_message.reply_text("You can also donate to the person currently running me " "[here]({})".format(DONATION_LINK), parse_mode=ParseMode.MARKDOWN) else: try: bot.send_message(user.id, DONATE_STRING, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True) update.effective_message.reply_text("I've PM'ed you about donating to my creator!") except Unauthorized: update.effective_message.reply_text("Contact me in PM first to get donation information.")
Example #12
Source File: core.py From CindicatorArbitrageBot with GNU General Public License v3.0 | 6 votes |
def notify(bot, job): """ Send notification to user Args: :param bot: <telegram.Bot> bot instance :param job: <telegram.ext.jobqueue.Job> user's job instance """ res = crawl(job.context['chat_id']) if len(res) > 0: try: bot.send_message(chat_id=job.context['chat_id'], text=_generate_string(res), parse_mode=messages.MARKDOWN) except Unauthorized: job.schedule_removal() mq.update_setting(job.context['chat_id'], setting=base_config.NOTIFICATIONS, value=False) except TimedOut: logger.warning('chat_id: {}; error: {}'.format(job.context['chat_id'], 'Time out while sending notification')) except Exception as e: logger.warning('chat_id: {}; error: {}\n' '{}'.format(job.context['chat_id'], str(e), format_exc()))
Example #13
Source File: __main__.py From tgbot with GNU General Public License v3.0 | 5 votes |
def error_callback(bot, update, error): try: raise error except Unauthorized: print("no nono1") print(error) # remove update.message.chat_id from conversation list except BadRequest: print("no nono2") print("BadRequest caught") print(error) # handle malformed requests - read more below! except TimedOut: print("no nono3") # handle slow connection problems except NetworkError: print("no nono4") # handle other connection problems except ChatMigrated as err: print("no nono5") print(err) # the chat_id of a group has changed, use e.new_chat_id instead except TelegramError: print(error) # handle all other telegram related errors
Example #14
Source File: log_channel.py From Marie-2.0-English with GNU General Public License v3.0 | 5 votes |
def setlog(bot: Bot, update: Update): message = update.effective_message # type: Optional[Message] chat = update.effective_chat # type: Optional[Chat] if chat.type == chat.CHANNEL: message.reply_text("Now, forward the /setlog to the group you want to tie this channel to!") elif message.forward_from_chat: sql.set_chat_log_channel(chat.id, message.forward_from_chat.id) try: message.delete() except BadRequest as excp: if excp.message == "Message to delete not found": pass else: LOGGER.exception("Error deleting message in log channel. Should work anyway though.") try: bot.send_message(message.forward_from_chat.id, "This channel has been set as the log channel for {}.".format( chat.title or chat.first_name)) except Unauthorized as excp: if excp.message == "Forbidden: bot is not a member of the channel chat": bot.send_message(chat.id, "Successfully set log channel!") else: LOGGER.exception("ERROR in setting the log channel.") bot.send_message(chat.id, "Successfully set log channel!") else: message.reply_text("The steps to set a log channel are:\n" " - add bot to the desired channel\n" " - send /setlog to the channel\n" " - forward the /setlog to the group\n")
Example #15
Source File: log_channel.py From tgbot with GNU General Public License v3.0 | 5 votes |
def setlog(bot: Bot, update: Update): message = update.effective_message # type: Optional[Message] chat = update.effective_chat # type: Optional[Chat] if chat.type == chat.CHANNEL: message.reply_text("Now, forward the /setlog to the group you want to tie this channel to!") elif message.forward_from_chat: sql.set_chat_log_channel(chat.id, message.forward_from_chat.id) try: message.delete() except BadRequest as excp: if excp.message == "Message to delete not found": pass else: LOGGER.exception("Error deleting message in log channel. Should work anyway though.") try: bot.send_message(message.forward_from_chat.id, "This channel has been set as the log channel for {}.".format( chat.title or chat.first_name)) except Unauthorized as excp: if excp.message == "Forbidden: bot is not a member of the channel chat": bot.send_message(chat.id, "Successfully set log channel!") else: LOGGER.exception("ERROR in setting the log channel.") bot.send_message(chat.id, "Successfully set log channel!") else: message.reply_text("The steps to set a log channel are:\n" " - add bot to the desired channel\n" " - send /setlog to the channel\n" " - forward the /setlog to the group\n")
Example #16
Source File: __main__.py From Marie-2.0-English with GNU General Public License v3.0 | 5 votes |
def error_callback(bot, update, error): try: raise error except Unauthorized: print("no nono1") print(error) # remove update.message.chat_id from conversation list except BadRequest: print("no nono2") print("BadRequest caught") print(error) # handle malformed requests - read more below! except TimedOut: print("no nono3") # handle slow connection problems except NetworkError: print("no nono4") # handle other connection problems except ChatMigrated as err: print("no nono5") print(err) # the chat_id of a group has changed, use e.new_chat_id instead except TelegramError: print(error) # handle all other telegram related errors
Example #17
Source File: ezstickerbot.py From ez-sticker-bot with MIT License | 5 votes |
def sticker_received(update: Update, context: CallbackContext): message = update.message user_id = message.from_user.id # check spam filter cooldown_info = user_on_cooldown(user_id) if cooldown_info[0]: minutes = int(config['spam_interval'] / 60) message_text = get_message(user_id, 'spam_limit_reached').format(config['spam_max'], minutes, cooldown_info[1], cooldown_info[2]) message.reply_markdown(message_text) return # check if sticker is animated if message.sticker.is_animated: animated_sticker_received(update, context) return sticker_id = message.sticker.file_id # feedback to show bot is processing bot.send_chat_action(user_id, 'upload_document') try: download_path = download_file(sticker_id) image = Image.open(download_path) create_sticker_file(message, image, context) # delete local file os.remove(download_path) except Unauthorized: pass except TelegramError: message.reply_text(get_message(user_id, "send_timeout")) except FileNotFoundError: # if file does not exist ignore pass
Example #18
Source File: echobot.py From bale-bot-samples with Apache License 2.0 | 5 votes |
def main(): """Run the bot.""" global update_id # Telegram Bot Authorization Token bot = telegram.Bot(token='TOKEN', base_url="https://tapi.bale.ai/") # get the first pending update_id, this is so we can skip over it in case # we get an "Unauthorized" exception. try: bot.delete_webhook() update_id = bot.get_updates()[0].update_id except IndexError: update_id = None # Enable logging logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.DEBUG) while True: try: echo(bot) sleep(2) except NetworkError: sleep(1) except Unauthorized: # The user has removed or blocked the bot. update_id += 1
Example #19
Source File: __main__.py From SkittBot with GNU General Public License v3.0 | 5 votes |
def error_callback(bot, update, error): try: raise error except Unauthorized: print("no nono1") print(error) # remove update.message.chat_id from conversation list except BadRequest: print("no nono2") print("BadRequest caught") print(error) # handle malformed requests - read more below! except TimedOut: print("no nono3") # handle slow connection problems except NetworkError: print("no nono4") # handle other connection problems except ChatMigrated as err: print("no nono5") print(err) # the chat_id of a group has changed, use e.new_chat_id instead except TelegramError: print(error) # handle all other telegram related errors
Example #20
Source File: ezstickerbot.py From ez-sticker-bot with MIT License | 5 votes |
def broadcast_thread(context: CallbackContext): # check that message was included with the job obj if context.job.context is None: print("Broadcast thread created without message stored in job context") return global config index = 0 for user_id in list(users): # check if user is opted in opt_in = get_user_config(user_id, "opt_in") # catch any errors thrown by users who have stopped bot try: if opt_in and not config['override_opt_out']: bot.send_message(chat_id=int(user_id), text=context.job.context, parse_mode='HTML', disable_web_page_preview=True) # send opt out message if config['send_opt_out_message']: bot.send_message(chat_id=int(user_id), text=get_message(user_id, "opt_out_info")) except Unauthorized: pass except TelegramError as e: logger.warning("Error '{}' when broadcasting message to {}".format(e.message, user_id)) index += 1 if index >= config['broadcast_batch_size']: time.sleep(config['broadcast_batch_interval']) index = 0
Example #21
Source File: poll.py From ultimate-poll-bot with MIT License | 5 votes |
def remove_old_references(session, bot, poll, user): """Remove old references in private chats.""" references = ( session.query(Reference) .filter(Reference.poll == poll) .filter(Reference.user == user) .all() ) for reference in references: try: bot.delete_message( chat_id=reference.user_id, message_id=reference.message_id ) except Unauthorized: session.delete(reference) except BadRequest as e: if ( e.message.startswith("Message_id_invalid") or e.message.startswith("Message can't be edited") or e.message.startswith("Message to edit not found") or e.message.startswith("Chat not found") or e.message.startswith("Can't access the chat") ): session.delete(reference) session.commit()
Example #22
Source File: common.py From NanoWalletBot with BSD 3-Clause "New" or "Revised" License | 5 votes |
def message_markdown(bot, chat_id, message): try: bot.sendMessage(chat_id=chat_id, text=message, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True) except BadRequest: bot.sendMessage(chat_id=chat_id, text=replace_unsafe(message), parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True) except RetryAfter: sleep(240) bot.sendMessage(chat_id=chat_id, text=message, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True) except TimedOut as e: sleep(60) bot.sendMessage(chat_id=chat_id, text=message, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True) except Unauthorized as e: sleep(0.25) except NetworkError as e: sleep(30) bot.sendMessage(chat_id=chat_id, text=message, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True) except Exception as e: sleep(1) bot.sendMessage(chat_id=chat_id, text=message, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True)
Example #23
Source File: updater.py From telegram-robot-rss with Mozilla Public License 2.0 | 5 votes |
def _bootstrap(self, max_retries, clean, webhook_url, allowed_updates, cert=None): retries = 0 while 1: try: if clean: # Disable webhook for cleaning self.bot.delete_webhook() self._clean_updates() sleep(1) self.bot.set_webhook( url=webhook_url, certificate=cert, allowed_updates=allowed_updates) except (Unauthorized, InvalidToken): raise except TelegramError: msg = 'error in bootstrap phase; try={0} max_retries={1}'.format(retries, max_retries) if max_retries < 0 or retries < max_retries: self.logger.warning(msg) retries += 1 else: self.logger.exception(msg) raise else: break sleep(1)
Example #24
Source File: log_channel.py From EmiliaHikari with GNU General Public License v3.0 | 5 votes |
def setlog(update, context): message = update.effective_message # type: Optional[Message] chat = update.effective_chat # type: Optional[Chat] if chat.type == chat.CHANNEL: send_message(update.effective_message, tl(update.effective_message, "Sekarang, teruskan /setlog ke grup yang Anda ingin ikat saluran ini!")) elif message.forward_from_chat: sql.set_chat_log_channel(chat.id, message.forward_from_chat.id) try: message.delete() except BadRequest as excp: if excp.message == "Message to delete not found": pass else: LOGGER.exception("Error deleting message in log channel. Should work anyway though.") try: context.bot.send_message(message.forward_from_chat.id, tl(update.effective_message, "Saluran ini telah ditetapkan sebagai saluran log untuk {}.").format( chat.title or chat.first_name)) except Unauthorized as excp: if excp.message == "Forbidden: bot is not a member of the channel chat": context.bot.send_message(chat.id, tl(update.effective_message, "Gagal menyetel saluran log!\nSaya mungkin bukan admin di channel tersebut.")) sql.stop_chat_logging(chat.id) return else: LOGGER.exception("ERROR in setting the log channel.") context.bot.send_message(chat.id, tl(update.effective_message, "Berhasil mengatur saluran log!")) else: send_message(update.effective_message, tl(update.effective_message, "Langkah-langkah untuk mengatur saluran log adalah:\n" " - tambahkan bot ke saluran yang diinginkan\n" " - Kirimkan /setlog ke saluran\n" " - Teruskan /setlog ke grup\n"))
Example #25
Source File: log_channel.py From SkittBot with GNU General Public License v3.0 | 5 votes |
def setlog(bot: Bot, update: Update): message = update.effective_message # type: Optional[Message] chat = update.effective_chat # type: Optional[Chat] if chat.type == chat.CHANNEL: message.reply_text("Now, forward the /setlog to the group you want to tie this channel to!") elif message.forward_from_chat: sql.set_chat_log_channel(chat.id, message.forward_from_chat.id) try: message.delete() except BadRequest as excp: if excp.message == "Message to delete not found": pass else: LOGGER.exception("Error deleting message in log channel. Should work anyway though.") try: bot.send_message(message.forward_from_chat.id, "This channel has been set as the log channel for {}.".format( chat.title or chat.first_name)) except Unauthorized as excp: if excp.message == "Forbidden: bot is not a member of the channel chat": bot.send_message(chat.id, "Successfully set log channel!") else: LOGGER.exception("ERROR in setting the log channel.") bot.send_message(chat.id, "Successfully set log channel!") else: message.reply_text("The steps to set a log channel are:\n" " - add bot to the desired channel\n" " - send /setlog to the channel\n" " - forward the /setlog to the group\n")
Example #26
Source File: session.py From ultimate-poll-bot with MIT License | 4 votes |
def ignore_exception(exception): """Check whether we can safely ignore this exception.""" if isinstance(exception, BadRequest): if ( exception.message.startswith("Query is too old") or exception.message.startswith("Have no rights to send a message") or exception.message.startswith("Message_id_invalid") or exception.message.startswith("Message identifier not specified") or exception.message.startswith("Schedule_date_invalid") or exception.message.startswith("Message to edit not found") or exception.message.startswith( "Message is not modified: specified new message content" ) ): return True if isinstance(exception, Unauthorized): if exception.message.lower() == "forbidden: bot was blocked by the user": return True if exception.message.lower() == "forbidden: message_author_required": return True if ( exception.message.lower() == "forbidden: bot is not a member of the supergroup chat" ): return True if exception.message.lower() == "forbidden: user is deactivated": return True if exception.message.lower() == "forbidden: bot was kicked from the group chat": return True if ( exception.message.lower() == "forbidden: bot was kicked from the supergroup chat" ): return True if exception.message.lower() == "forbidden: chat_write_forbidden": return True if isinstance(exception, TimedOut): return True if isinstance(exception, RetryAfter): return True return False
Example #27
Source File: common.py From NanoWalletBot with BSD 3-Clause "New" or "Revised" License | 4 votes |
def push(bot, chat_id, message): try: bot.sendMessage(chat_id=chat_id, text=message, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True) except BadRequest as e: try: bot.sendMessage(chat_id=chat_id, text=replace_unsafe(message), parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True) except BadRequest: bot.sendMessage(chat_id=chat_id, text=message.replace("_", "\_"), parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True) except RetryAfter as e: sleep(240) bot.sendMessage(chat_id=chat_id, text=replace_unsafe(message), parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True) except TimedOut as e: sleep(60) bot.sendMessage(chat_id=chat_id, text=replace_unsafe(message), parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True) except Unauthorized as e: sleep(0.25) except NetworkError as e: sleep(30) bot.sendMessage(chat_id=chat_id, text=replace_unsafe(message), parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True) except Exception as e: sleep(1) try: bot.sendMessage(chat_id=chat_id, text=message, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True) except: sleep(2.5) bot.sendMessage(chat_id=chat_id, text=message, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True)
Example #28
Source File: admin.py From sticker-finder with MIT License | 4 votes |
def broadcast(bot, update, session, chat, user): """Broadcast a message to all users.""" message = update.message.text.split(" ", 1)[1].strip() users = ( session.query(User) .filter(User.notifications.is_(True)) .order_by(User.id.asc()) .all() ) call_tg_func( update.message.chat, "send_message", args=[f"Sending broadcast to {len(users)} chats."], ) deleted = 0 count = 0 for user in users: try: count += 1 if count % 250 == 0: update.message.chat.send_message(f"{count} users") bot.send_message( user.id, message, parse_mode="Markdown", reply_markup=ReplyKeyboardRemove(), ) # The chat doesn't exist any longer, delete it except BadRequest as e: if e.message == "Chat not found": # noqa deleted += 1 continue # We are not allowed to contact this user. except Unauthorized: deleted += 1 session.delete(user) continue # Sleep one second to not trigger flood prevention time.sleep(0.07) call_tg_func( update.message.chat, "send_message", [f"All messages sent. Deleted {deleted} chats."], {"reply_markup": ReplyKeyboardRemove()}, )
Example #29
Source File: reporting.py From Marie-2.0-English with GNU General Public License v3.0 | 4 votes |
def report(bot: Bot, update: Update) -> str: message = update.effective_message # type: Optional[Message] chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] if chat and message.reply_to_message and sql.chat_should_report(chat.id): reported_user = message.reply_to_message.from_user # type: Optional[User] chat_name = chat.title or chat.first or chat.username admin_list = chat.get_administrators() if chat.username and chat.type == Chat.SUPERGROUP: msg = "<b>{}:</b>" \ "\n<b>Reported user:</b> {} (<code>{}</code>)" \ "\n<b>Reported by:</b> {} (<code>{}</code>)".format(html.escape(chat.title), mention_html( reported_user.id, reported_user.first_name), reported_user.id, mention_html(user.id, user.first_name), user.id) link = "\n<b>Link:</b> " \ "<a href=\"http://telegram.me/{}/{}\">click here</a>".format(chat.username, message.message_id) should_forward = False else: msg = "{} is calling for admins in \"{}\"!".format(mention_html(user.id, user.first_name), html.escape(chat_name)) link = "" should_forward = True for admin in admin_list: if admin.user.is_bot: # can't message bots continue if sql.user_should_report(admin.user.id): try: bot.send_message(admin.user.id, msg + link, parse_mode=ParseMode.HTML) if should_forward: message.reply_to_message.forward(admin.user.id) if len(message.text.split()) > 1: # If user is giving a reason, send his message too message.forward(admin.user.id) except Unauthorized: pass except BadRequest as excp: # TODO: cleanup exceptions LOGGER.exception("Exception while reporting user") return msg return ""
Example #30
Source File: feds.py From EmiliaHikari with GNU General Public License v3.0 | 4 votes |
def fed_broadcast(update, context): msg = update.effective_message # type: Optional[Message] user = update.effective_user # type: Optional[User] chat = update.effective_chat # type: Optional[Chat] args = context.args if chat.type == 'private': send_message(update.effective_message, tl(update.effective_message, "Perintah ini di khususkan untuk grup, bukan pada PM!")) return if args: chat = update.effective_chat # type: Optional[Chat] fed_id = sql.get_fed_id(chat.id) fedinfo = sql.get_fed_info(fed_id) # Parsing md raw_text = msg.text args = raw_text.split(None, 1) # use python's maxsplit to separate cmd and args txt = args[1] offset = len(txt) - len(raw_text) # set correct offset relative to command text_parser = markdown_parser(txt, entities=msg.parse_entities(), offset=offset) text = text_parser try: broadcaster = user.first_name except: broadcaster = user.first_name + " " + user.last_name text += "\n\n- {}".format(mention_markdown(user.id, broadcaster)) chat_list = sql.all_fed_chats(fed_id) failed = 0 for chat in chat_list: title = tl(chat, "*Siaran baru dari Federasi {}*\n").format(fedinfo['fname']) try: context.bot.sendMessage(chat, title + text, parse_mode="markdown") except TelegramError: try: dispatcher.bot.getChat(chat) except Unauthorized: failed += 1 sql.chat_leave_fed(chat) LOGGER.info("Chat {} has leave fed {} because bot is kicked".format(chat, fedinfo['fname'])) continue failed += 1 LOGGER.warning("Couldn't send broadcast to {}".format(str(chat))) send_text = tl(update.effective_message, "Siaran Federasi selesai.") if failed >= 1: send_text += tl(update.effective_message, "{} grup gagal menerima pesan, mungkin karena meninggalkan federasi.").format(failed) send_message(update.effective_message, send_text)