本文整理汇总了Python中telegram.error.NetworkError方法的典型用法代码示例。如果您正苦于以下问题:Python error.NetworkError方法的具体用法?Python error.NetworkError怎么用?Python error.NetworkError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类telegram.error
的用法示例。
在下文中一共展示了error.NetworkError方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: push_simple
# 需要导入模块: from telegram import error [as 别名]
# 或者: from telegram.error import NetworkError [as 别名]
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)
示例2: get_invalid_channel_access
# 需要导入模块: from telegram import error [as 别名]
# 或者: from telegram.error import NetworkError [as 别名]
def get_invalid_channel_access(bot):
configs = helper_database.get_all_channel_config()
invalid_list = []
for config in configs:
channel_id = int(config[0])
admin_id = int(config[5])
try:
chat_members = bot.get_chat_administrators(chat_id=channel_id).result()
except TimedOut:
pass
except NetworkError:
pass
except:
invalid_list.append(config)
return invalid_list
示例3: error_callback
# 需要导入模块: from telegram import error [as 别名]
# 或者: from telegram.error import NetworkError [as 别名]
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
示例4: fetchTelegramUpdates
# 需要导入模块: from telegram import error [as 别名]
# 或者: from telegram.error import NetworkError [as 别名]
def fetchTelegramUpdates(self):
self.logger.info('Setting up telegram thread')
while True:
try:
# request updates after the last update_id
# timeout: how long to poll for messages
for update in self.bot.getUpdates(offset=self.update_id, timeout=10):
# skip updates without a message
if not update.message:
continue
# chat_id is required to reply to any message
chat_id = update.message.chat_id
self.update_id = update.update_id + 1
message = update.message
# skip messages from non-owner
if message.from_user.id not in self.config['telegram']['owner_ids']:
self.logger.warn('Received message from unknown user "%s": "%s"' % (message.from_user, message.text))
message.reply_text("I'm sorry, Dave. I'm afraid I can't do that.")
continue
self.logger.info('Received message from user "%s": "%s"' % (message.from_user, message.text))
self.performCommand(message)
except NetworkError as e:
time.sleep(1)
except Exception as e:
self.logger.warn(str(e))
self.logger.warn(traceback.format_exc())
time.sleep(1)
示例5: message_markdown
# 需要导入模块: from telegram import error [as 别名]
# 或者: from telegram.error import NetworkError [as 别名]
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)
示例6: text_reply
# 需要导入模块: from telegram import error [as 别名]
# 或者: from telegram.error import NetworkError [as 别名]
def text_reply(update, text):
try:
update.message.reply_text(text)
except TimedOut as e:
sleep(60)
update.message.reply_text(text)
except NetworkError as e:
sleep(30)
update.message.reply_text(text)
except Exception as e:
sleep(1)
update.message.reply_text(text)
示例7: main
# 需要导入模块: from telegram import error [as 别名]
# 或者: from telegram.error import NetworkError [as 别名]
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
示例8: main
# 需要导入模块: from telegram import error [as 别名]
# 或者: from telegram.error import NetworkError [as 别名]
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
示例9: error_callback
# 需要导入模块: from telegram import error [as 别名]
# 或者: from telegram.error import NetworkError [as 别名]
def error_callback(update, context):
# add all the dev user_ids in this list. You can also add ids of channels or groups.
devs = [OWNER_ID]
# we want to notify the user of this problem. This will always work, but not notify users if the update is an
# callback or inline query, or a poll update. In case you want this, keep in mind that sending the message
# could fail
if update.effective_message:
text = "Hey. I'm sorry to inform you that an error happened while I tried to handle your update. " \
"My developer(s) will be notified."
update.effective_message.reply_text(text)
# This traceback is created with accessing the traceback object from the sys.exc_info, which is returned as the
# third value of the returned tuple. Then we use the traceback.format_tb to get the traceback as a string, which
# for a weird reason separates the line breaks in a list, but keeps the linebreaks itself. So just joining an
# empty string works fine.
trace = "".join(traceback.format_tb(sys.exc_info()[2]))
# lets try to get as much information from the telegram update as possible
payload = ""
# normally, we always have an user. If not, its either a channel or a poll update.
if update.effective_user:
payload += f' with the user {mention_html(update.effective_user.id, update.effective_user.first_name)}'
# there are more situations when you don't get a chat
if update.effective_chat:
payload += f' within the chat <i>{update.effective_chat.title}</i>'
if update.effective_chat.username:
payload += f' (@{update.effective_chat.username})'
# but only one where you have an empty payload by now: A poll (buuuh)
if update.poll:
payload += f' with the poll id {update.poll.id}.'
# lets put this in a "well" formatted text
text = f"Hey.\n The error <code>{context.error}</code> happened{payload}. The full traceback:\n\n<code>{trace}" \
f"</code>"
# and send it to the dev(s)
for dev_id in devs:
context.bot.send_message(dev_id, text, parse_mode=ParseMode.HTML)
# we raise the error again, so the logger module catches it. If you don't use the logger module, use it.
try:
raise context.error
except Unauthorized:
# remove update.message.chat_id from conversation list
LOGGER.exception('Update "%s" caused error "%s"', update, context.error)
except BadRequest:
# handle malformed requests - read more below!
LOGGER.exception('Update "%s" caused error "%s"', update, context.error)
except TimedOut:
# handle slow connection problems
LOGGER.exception('Update "%s" caused error "%s"', update, context.error)
except NetworkError:
# handle other connection problems
LOGGER.exception('Update "%s" caused error "%s"', update, context.error)
except ChatMigrated as e:
# the chat_id of a group has changed, use e.new_chat_id instead
LOGGER.exception('Update "%s" caused error "%s"', update, context.error)
except TelegramError:
# handle all other telegram related errors
LOGGER.exception('Update "%s" caused error "%s"', update, context.error)
示例10: call_tg_func
# 需要导入模块: from telegram import error [as 别名]
# 或者: from telegram.error import NetworkError [as 别名]
def call_tg_func(
tg_object: object, function_name: str, args: list = None, kwargs: dict = None
):
"""Call a tg object member function.
We need to handle those calls in case we get rate limited.
"""
current_try = 1
tries = 4
exception = None
while current_try < tries:
try:
args = args if args else []
kwargs = kwargs if kwargs else {}
breadcrumbs.record(
data={"action": f"Starting: {datetime.now()}"}, category="info"
)
retrieved_object = getattr(tg_object, function_name)(*args, **kwargs)
return retrieved_object
except (TimedOut, NetworkError) as e:
# Can't update message. just ignore it
if "Message to edit not found" in str(
e
) or "Message is not modified" in str(e):
raise e
timeout = 2 * current_try
breadcrumbs.record(
data={"action": f"Exception: {datetime.now()}"}, category="info"
)
logger = logging.getLogger()
logger.info(
f"Try {current_try}: Got telegram exception waiting {timeout} secs."
)
logger.info(e.message)
if config["logging"]["debug"]:
sentry.captureException()
time.sleep(timeout)
current_try += 1
exception = e
pass
raise exception
示例11: push
# 需要导入模块: from telegram import error [as 别名]
# 或者: from telegram.error import NetworkError [as 别名]
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)