Telethon authorization Python - python

I have the following problem: I am trying to authorize a telegram client using a session created by telethon. When you run the code in the console, as befits, the phone number associated with the account is requested, followed by the confirmation code received from Telegram. And after entering the confirmation code, nothing happens, although a message about successful authorization should appear. After a few minutes of waiting for the program to work, a message about Incomplete login attempt arrives in the Telegram. Can you tell me what's the matter?
This is my code for making session:
from telethon import TelegramClient, events
api_id = MY_API_ID
api_hash = "MY_API_HASH"
client = TelegramClient('first_session', api_id, api_hash)
#client.on(events.NewMessage(outgoing=True, pattern=None))
async def greeting(event):
chat = await event.get_chat()
await client.send_message(chat, "Hello, World!")
client.start()
client.run_until_disconnected()
And results of launching the program in the terminal in the attached image
Launching in console

Perhaps the problem may be that you are not waiting for the confirmation code request to appear and complete before running the rest of the code. To solve this problem, you need to wrap the run_until_disconnected method in an asynchronous context and use the await keyword to wait for the confirmation code to be requested.
Try the code:
from telethon import TelegramClient, events
api_id = MY_API_ID
api_hash = "MY_API_HASH"
client = TelegramClient('first_session', api_id, api_hash)
#client.on(events.NewMessage(outgoing=True, pattern=None))
async def greeting(event):
chat = await event.get_chat()
await client.send_message(chat, "Hello, World!")
async def main():
await client.start()
await client.run_until_disconnected()
asyncio.run(main())

The question is removed. For full authorization via telethon , you need to enter the method .start() pass the password="12345" parameter, where 12345 is the two-factor authentication password.

Related

How to run discorn.py in a loop without closing the client at the end of each loop

What I need
I need a function that will run in a loop and send messages to discord channel
Problem
I have a function that sends messages to a discord channel
def send_discord(msg):
token = '0000000000000000000000000000000000'
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
#client.event
async def on_ready():
channel = client.get_channel(000000000000000)
await channel.send(msg)
await client.close()
client.run(token)
I need to run this function in a loop to get messages info and send it
At the moment I need to open the discord client each time before sending a messge. And then close it after the message is sent. This takes lots of time
If I don't close the client after sending the message - the program stops.
Question
How can I run my function in a loop without opening and closing it each time?
Why not use webhooks?
from discord_webhook import DiscordWebhook
def send_discord(msg)
webhook = DiscordWebhook(url='your webhook url', content=msg)
webhook.execute() # Send a message using the webhook
You can make a webhook just for a specific channel and use it to send messages. It doesn't need to login to discord and just needs the webhook url.
Read more about the module here:
https://github.com/lovvskillz/python-discord-webhook
Why don't you use the discord.on_message event!
#client.event
async def on_message(ctx, message):
if ctx.channel.id != CHANNEL_ID: return
# YOUR FUNCTION HERE

Telegram does not send authorization code if the request was sent from Telethon code

I am trying to do an small test using Telethon from a Thread but when requesting the authorization code to Telegram, it never arrives in my Telegram chat. Here is the code:
import asyncio
from threading import Thread
from telethon import TelegramClient
from telethon.sessions import StringSession
phone = "+5312345678"
api_id = 12345
api_hash = "xxxxxxxx"
def sync(func):
def wrapper(*args, **kwargs):
loop = asyncio.new_event_loop()
loop.run_until_complete(func(*args, **kwargs))
return wrapper
#sync
async def main():
client = TelegramClient(StringSession(), api_id, api_hash)
await client.connect()
res = await client.send_code_request(phone) # <- REQUESTED HERE (I also tried forcing SMS)
await client.disconnect() # no try/finally to keep example simple
print("hash:", res.phone_code_hash)
Thread(target=main).start()
The code executes without errors and the hash is printed, but the code never arrives in Telegram, so my question is if there is something wrong with the code? am I doing something wrong in the usage of async Telethon API inside a thread or it is just Telegram blocking me for something similar to:
Telegram does not send authorization code if the request was sent from telethon code hosted on Heroku
so, after some more tests, it seems the issue is because I am disconnecting right after requesting the code:
await client.disconnect()
and it seems Telegram doesn't sends the code if it detects the client dropped the connection right away after requesting it, maybe because it is suspicious (ex. an script requesting codes for a lot of users in a batch)

Pyrogram telegram API (not bot api)

i am using Pyrogram to work with telegram API.
I have succeed to join channel.
I have a task to add message handler and receive messages in channel.
But the message handler is not invoked when message arrives (i am the owner of channel)
The code:
import asyncio
from pyrogram import Client
import time
from pyrogram.handlers import MessageHandler, RawUpdateHandler
api_id = "xx"
api_hash = "xx"
def my_handler(client, message):
message.forward("me")
print('sent msg')
async def main():
async with Client("my_account", api_id, api_hash) as app:
a = await app.get_chat('test2k3')
msg_handler = MessageHandler(my_handler)
app.add_handler(msg_handler)
await app.join_chat(str(a.id))
print(f'joined chat ' + str(a.id))
while True:
time.sleep(2.4)
asyncio.get_event_loop().run_until_complete(main())
Sleeping while the client runs halts it until the sleep is over. Pyrogram itself will already keep itself alive until Ctrl and C is pressed. Remove your while True sleep loop.
as recommended by sudden_appearance
use asyncio.sleep() inside async functions instead of time.sleep()

Send message to telegram channel with telethon and get mobile notification

I want to use telethon to send messages to my own private channel, and receive mobile push notifications when the python script posts a message. With the below code I'm able to send the messages, but I do not receive any mobile push notifications. I've turned on all notification settings in the mobile app. I have been googling around for 'telethon push notifications', without any luck.
from telethon import TelegramClient
api_id = 'api_id'
api_hash = 'api_hash'
username = 'username'
channel_invite_link = 'channel invite link'
async def func():
entity = await client.get_entity(channel_invite_link)
await client.send_message(entity=entity, message="Hi")
with TelegramClient(username, api_id, api_hash) as client:
client.loop.run_until_complete(func())
Just use the silent argument, i.e.:
await client.send_message(entity=entity, message="Hi", silent=False)

How to send message to Telegram channel in Telethon

Am trying to send a message to a Telegram channel after a new message event is invoked in another. The code i have below utilizes the channel name as the entity but it doesn't work all the time. Any ideas how i would go about it in better and effecient way.
#client.on(events.NewMessage(chats=channel))
async def my_event_handler(event):
values = formatter(event.raw_text)
await client.send_message('destination', template.format(coin=values[0], buy=values[1]))
client.start()
client.run_until_disconnected()
This is the Documentation :
So i've send a message that said "Hello python" with the username "abdx".
client = TelegramClient('session_name',
api_id,
api_hash,
)
client.start()
destination_user_username='abdx'
entity=client.get_entity(destination_user_username)
client.send_message(entity=entity,message="Hello python")
By Alihossein shahabi.

Categories