I'm trying to write a simple script to close an opened session using Telethon lib:
from telethon import TelegramClient, events, sync
from telethon.sync import TelegramClient
from telethon import functions, types
import time
api_id = "YYYY"
api_hash = "XXXXX"
client = TelegramClient('#example', api_id, api_hash)
client.start()
#With this I can get all the necesary info about current sessions
result = client(functions.account.GetAuthorizationsRequest())
print(result.stringify())
#With this I should be able to close the sessions using it's hash:
result = client(functions.account.ResetAuthorizationRequest(hash=-123456789101112))
print(result)
But I get this error:
telethon.errors.rpcerrorlist.FreshResetAuthorisationForbiddenError:
The current session is too new and cannot be used to reset other
authorisations yet (caused by ResetAuthorizationRequest)
I initialized the session like 1h ago; I tried put some time.sleep before the ResetAuthorizationRequest, but that didn't did the trick. What should I do in order to close a session? Should I wait more? In that case, what's the aproximated time I need to wait?
Related
as the title states, I'm writing a Slack Bot in Python and using NGROK to host it locally. I'm not super experienced with decorators, and I can get the bot posting messages in slack, however I can't seem to handle two events at once. For example, I want to handle a message and have the message keep repeating in slack until a thumbs up reaction is added to that message. The issue is I cannot figure out how to handle an event while another event is still running, please see the following code:
rom slack import WebClient
import os
import time
from pathlib import Path
from dotenv import load_dotenv
from flask import Flask
from slackeventsapi import SlackEventAdapter
env_path = Path('.') / '.env'
load_dotenv(dotenv_path=env_path)
app = Flask(__name__)
slack_event_adapter = SlackEventAdapter(
os.environ['SIGNING_SECRET'],'/slack/events',app)
client = WebClient(token=os.environ['SLACK_TOKEN'])
BOT_ID = client.api_call("auth.test")['user_id']
state = {}
#slack_event_adapter.on('message')
def handle_message(event_data):
message = event_data.get('event', {})
channel_id = message.get('channel')
user_id = message.get('user')
text = message.get('text')
messageid = message.get('ts')
state[messageid] = {"channel_id": channel_id, "user_id": user_id, "text": text}
if BOT_ID != user_id:
if text[0:12] == ":red_circle:":
time.sleep(5)
client.chat_postMessage(channel=channel_id, text=text)
if text[0:21] == ":large_yellow_circle:":
client.chat_postMessage(channel=channel_id, text="it's a yellow question!")
if text[0:14] == ":white_circle:":
client.chat_postMessage(channel=channel_id, text="it's a white question!")
#slack_event_adapter.on('reaction_added')
def reaction_added(event_data):
reaction = event_data.get('event',{})
emoji = reaction.get('reaction')
emoji_id = reaction.get('item',{}).get('ts')
emoji_channel_id = reaction.get('item',{}).get('channel')
client.chat_postMessage(channel=emoji_channel_id, text=emoji)
for message_id, message_data in state.items():
channel_id = message_data["channel_id"]
text = message_data["text"]
client.chat_postMessage(channel=channel_id, text=text)
print(message_id,message_data)
if __name__ == "__main__":
app.run(debug=True)
I can handle individual events, but I cannot handle them while another is running. Please help! :)
Flask is a synchronous web framework.
When it's running a view handler, it uses up a web worker thread. If you does something like time.sleep(...), that worker thread will still be occupied and unavailable to handle other requests until the sleep finishes.
There are a couple options you can do here.
You can use Bolt for Python, which is a Python Slack library that natively support asynchronous even processing. Instead of time.sleep(), you can do await asyncio.sleep(...), which returns the thread to the async loop, and allow the worker thread to process other events.
If you already have an existing slack application and don't want to rewrite your entire codebase to Bolt, then you'll need to handle the event processing yourself. You can do this by doing your work in an ThreadLoopExecutor, or by building your own async event Queue mechanism, or use Celery. Or if your slack bot has very low volume, you can probably just add more web workers, and hope for the best that you don't run out of workers.
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 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())
This is my code
from telegram.ext import Updater, CommandHandler
import os
from pymongo import MongoClient
TOKEN = 'TOKEN'
def get_db(update, context):
cluster = MongoClient("mongodb+srv://testing:12345678#cluster0.gs9k5.mongodb.net/test?retryWrites=true&w=majority")
result = list(cluster.get_database('DBNAME')['COLLECTIONNAME'].find({}))
update.message.reply_text(str(result))
def main():
updater = Updater(TOKEN, use_context=True)
dp = updater.dispatcher
dp.add_handler(CommandHandler("getdb", get_db))
updater.start_webhook(listen="#.#.#.#",
port=int(PORT),
url_path=TOKEN)
updater.bot.setWebhook('https://MYHEROKUAPP.herokuapp.com/' + TOKEN)
updater.idle()
if __name__ == '__main__':
main()
Everytime I type /getdb, the bot doesn't give me any response. When I tried several experiments, Seems there's some Error on cluster variable. I used try except syntax, but the bot didn't show anything, even from the except and I couldn't found the Error name as well. And I'm using heroku server for the telegram bot. How to fix this?
You can connect to default db (which is the one defined in the connection string) and query the collections like this
client = MongoClient('connect-string')
db = client.get_default_database()
# 'collection_name' is the name of the Mongo collection
list = db.collection_name.find()
I'm not sure if you still have this issue, but the code seems to be okay so far.
Try logging the app info to the terminal to get a better idea of what the error is.
import logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)
It may be that your MongoDB Atlas is not allowing connection from the server you are running your code from. You can check your cluster to see if it allows access to the DB from your server. You can add the IP address of your server to the cluster to allow it succesfully access the data.
If the collection you're trying to display all items from is large, Telegram will throw an error because the ensuing message will be too long. Ensure that you're running your test with only a few items in your test database.
You should be ale to check your heroku logs or in your terminal to see what other errors might be happening
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.