I'm trying to get the latest message from a telegram channel with telethon and the following code:
import t_api,time,asyncio
from telethon import TelegramClient
from telethon.tl.functions.messages import GetHistoryRequest
async def get_message():
license_b="allow"
flag=0
try:
async with TelegramClient(t_api.username,t_api.api_id,t_api.api_hash) as client:
my_channel=await client.get_entity("channel_name")
while license_b=="allow":
history=await client(GetHistoryRequest(peer=my_channel,offset_id=0,offset_date=None,add_offset=0,limit=1,max_id=0,min_id=0,hash=0))
t1=history.messages[0].message
if flag==0:
sub_t1=t1
flag+=1
if sub_t1!=t1:
flag=0
checking_b(t1)
time.sleep(2)
except:
return False
asyncio.run(get_message())
I have to use this method due to the delay of about 30 seconds in receiving messages via streaming channels with many members.
And this code works well, but sometimes after a few hours, despite the try except function, program gets following error.
Telegram is having internal issues RpcCallFailError: Telegram is having internal issues, please try again later. (caused by GetHistoryRequest)
My question is how to prevent this error from occurring and how to handle it if it occurs, because try except dose not work.
Someone can help me?
Related
Hi I'm trying to make a telegram bot that edits its same message multiple times like BotFather does, but every time that I try it gives me this error:
telegram.error.BadRequest: Message is not modified: specified new message content and reply markup are exactly the same as a current content and reply markup of the message
Here is the code, I tried to make it as clear as possible.
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import *
from API import API_KEY
from bot_messages import *
updater = Updater(API_KEY, use_context=True)
dispatcher = updater.dispatcher
def start(update, context):
update.message.reply_text(WELCOME, reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("Ciao", callback_data="ciao")]]))
def ciao(update, context):
update.callback_query.edit_message_text("Ciao", reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("Dona!", callback_data="donate")]]))
def donate(update, context):
update.callback_query.edit_message_text("Dona", reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("Dona", callback_data="dona")]]))
dispatcher.add_handler(CommandHandler("start", start))
dispatcher.add_handler(CommandHandler("restart", start))
dispatcher.add_handler(CallbackQueryHandler(ciao))
dispatcher.add_handler(CallbackQueryHandler(donate))
updater.start_polling()
updater.idle()
Also can you tell me the proper way of making inline query handlers? Because if it is giving me error it could perhaps mean that I'm not doing it quite right. Thanks in advance.
In your snippet only the first CallbackQueryHandler will ever handle updates - please see the docs of Dispatcher.add_handler for details on how dispatcher decides which handler gets to handle an update.
That's why your code is trying to update the message with the unchanged text and you get that error.
To fix that, you can e.g. use the pattern argument of CallbackQueryhandler.
Disclaimer: I'm currently the maintainer of python-telegram-bot.
I have been able to login to Telegram and send messages to myself and also retrieve users from a group. But whenever I try to add members to a group, I get an error.
Here is my code
from pyrogram import Client
import asyncio
from pyrogram.errors import FloodWait
TARGET = 'intendingcouples_class'
async def main():
app = Client("my_account")
users = []
async with app:
async for member in app.get_chat_members(TARGET):
users.append(member.user.id)
print(users)
await app.add_chat_members('myenki', member.user.id)
asyncio.run(main())
When I run the above code, I get this error
pyrogram.errors.exceptions.flood_420.FloodWait: Telegram says: [420 FLOOD_WAIT_X] - A wait of 73958 seconds is required (caused by "channels.InviteToChannel")
Please, how do I solve this problem?
Your error is clear:
pyrogram.errors.exceptions.flood_420.FloodWait: Telegram says: [420 FLOOD_WAIT_X] - A wait of 73958 seconds is required (caused by "channels.InviteToChannel")
You'll have to wait 73958 seconds to be able to use the method again. Besides that, adding members against their will to random groups can get both your group, and your account permanently banned.
I'm creating a script that is posting a message to both discord and twitter, depending on some input. I have to methods (in separate .py files), post_to_twitter and post_to_discord. What I want to achieve is that both of these try to execute even if the other fails (e.g. if there is some exception with login).
Here is the relevant code snippet for posting to discord:
def post_to_discord(message, channel_name):
client = discord.Client()
#client.event
async def on_ready():
channel = # getting the right channel
await channel.send(message)
await client.close()
client.run(discord_config.token)
and here is the snippet for posting to twitter part (stripped from the try-except blocks):
def post_to_twitter(message):
auth = tweepy.OAuthHandler(twitter_config.api_key, twitter_config.api_key_secret)
auth.set_access_token(twitter_config.access_token, twitter_config.access_token_secret)
api = tweepy.API(auth)
api.update_status(message)
Now, both of these work perfectly fine on their own and when being called synchronously from the same method:
def main(message):
post_discord.post_to_discord(message)
post_tweet.post_to_twitter(message)
However, I just cannot get them to work concurrently (i.e. to try to post to twitter even if discord fails or vice-versa). I've already tried a couple of different approaches with multi-threading and with asyncio.
Among others, I've tried the solution from this question. But got an error No module named 'IPython'. When I omitted the IPython line, changed the methods to async, I got this error: RuntimeError: Cannot enter into task <ClientEventTask state=pending event=on_ready coro=<function post_to_discord.<locals>.on_ready at 0x7f0ee33e9550>> while another task <Task pending name='Task-1' coro=<main() running at post_main.py:31>> is being executed..
To be honest, I'm not even sure if asyncio would be the right approach for my use case, so any insight is much appreciated.
Thank you.
In this case running the two things in completely separate threads (and completely separate event loops) is probably the easiest option at your level of expertise. For example, try this:
import post_to_discord, post_to_twitter
import concurrent.futures
def main(message):
with concurrent.futures.ThreadPoolExecutor() as pool:
fut1 = pool.submit(post_discord.post_to_discord, message)
fut2 = pool.submit(post_tweet.post_to_twitter, message)
# here closing the threadpool will wait for both futures to complete
# make exceptions visible
for fut in (fut1, fut2):
try:
fut.result()
except Exception as e:
print("error: ", e)
I try to start pyrogram client with loop.create_task(app.start()) but get an error TypeError: a coroutine was expected, got <pyrogram.client.Client object at 0x7f8bb7580520>, how can I fix it? It worked fine year ago but now it doesnt
import asyncio
from pyrogram import Client
loop = asyncio.get_event_loop()
app = Client(
"aaaaa",
bot_token="token",
api_id=12,
api_hash="a"
)
loop.create_task(app.start())
Pyrogram Client already has an event loop, you don't need to create again. If you follow the documentation it's clear how to run the bot.
Also you can use the Pyrostarter to create a bot project.
Trying to build a Telegram Quiz Bot using pyTelegramBotAPI. I'm using sched to schedule the message Handler but i don't know how to stop the Message Handler and return to my Main Script which will scheudle the next Round.
Tryed to use timeout but it is not working!
My Code:
import telebot
import sched, time
def listen():
print("Send my your Answer")
#bot.message_handler(func=lambda message: True, content_types=['text'])
def command_default(m):
print(m.text)
bot.polling()
API_TOKEN = 'xxxx'
s = sched.scheduler(time.time, time.sleep)
bot = telebot.TeleBot(API_TOKEN)
s.enter(50, 1, listen)
s.run()
In this use case you have to use something called a Finite State Machine (FSM). You keep track of user states, such as one where the user is ready to send an answer.
This is already implemented in pyTelegramBotAPI, with the next_step_handler(). However, I suggest you instead create your own solution, as the one provided by the wrapper is quite buggy.
Here is an example (you can translate the page): https://groosha.gitbooks.io/telegram-bot-lessons/content/chapter11.html