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.
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 am trying to use Solana Py to connect to serum's dex and get order book updates. I am not sure how to do this. I had something working using serum-vial, but I'm trying to rewrite that library because it has caused me too many issues.
As a proof of concept, I am trying to get "SOL/USDC" to load in. So I am trying to get SOL/USDC's account info to load in the proper program Id. Here is my code:
import asyncio
from asyncstdlib import enumerate
from solana.rpc.websocket_api import connect
from solana.publickey import PublicKey
from solana.rpc.async_api import AsyncClient
from solana.rpc.commitment import Confirmed
async def main():
client = AsyncClient("https://psytrbhymqlkfrhudd.dev.genesysgo.net:8889/", Confirmed)
print("Connecting...")
await client.is_connected()
response = await client.get_account_info(
PublicKey("9xQeWvG816bUx9EPjHmaT23yvVM2ZWbrrpZb9PusVFin"),
encoding="base64"
)
for stake in response['result']:
print(stake)
await client.close()
asyncio.run(main())
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?
Is it possible to delete all chat history(messages) of my chat with bot.
So the console version be like:
import os
os.sys("clear") - if Linux
os.sys("cls") - if Windows
All I want is to delete all messages in chat using bot.
def deleteChat(message):
#delete chat code
First of all, if you want to delete history with a bot you should save message ids.
Otherwise, you could use an userbot (using an user account) for clearing it.
You can iter all chat messages and get their ids, and delete them in chunks of 100 messages each iteration.
Warning: itering message history of a chat is not possible with bots and BotAPI, because of Telegram limits. So you should use an MTProto API framework, with an user account as said before.
First of all, pyrogram library is needed for doing this (you could also use telethon), and instance a Client, then you can add an handler or start Client using with keyword. Then get all messages ids by itering the chat, and save them in a list. Finally, delete them using delete_messages Client method:
import time, asyncio
from pyrogram import Client, filters
app = Client(
"filename", # Will create a file named filename.session which will contain userbot "cache"
# You could also change "filename" to ":memory:" for better performance as it will write userbot session in ram
api_id=0, # You can get api_hash and api_id by creating an app on
api_hash="", # my.telegram.org/apps (needed if you use MTProto instead of BotAPI)
)
#app.on_message(filters.me & filters.command("clearchat") & ~filters.private)
async def clearchat(app_, msg):
start = time.time()
async for x in app_.iter_history(msg.chat.id, limit=1, reverse=True):
first = x.message_id
chunk = 98
ids = range(first, msg.message_id)
for _ in (ids[i:i+chunk] for i in range(0, len(ids), chunk)):
try:
asyncio.create_task(app_.delete_messages(msg.chat.id, _))
except:
pass
end = time.time() - start
vel = len(ids) / end
await msg.edit_text(f"{len(ids)} messages were successfully deleted in {end-start}s.\n{round(vel, 2)}mex/s")
app.run()
Once you start the userbot, add it in a group, and send "/clearchat". If the userbot has delete messages permission, it will start deleting all messages.
For pyrogram documentation see https://docs.pyrogram.org.
(however, you should not print all messages in the terminal, to avoid server overloading)
And the right code for clearing the console is this:
import os
def clear():
os.system("cls" if os.name == "nt" else "clear")
as seen in How to clear the interpreter console?.
P.S.
You can use the same code, adding bot_token="" parameter to Client, and deleting iter_history part, for deleting messages with a bot if you have the messages ids.
If in the future you'll want to receive messages from a group and print them, but you don't receive the message update, add the bot as admin in the group or disable bot privacy mode in BotFather.
For better pyrogram performance, you should install tgcrypto library.
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