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.
Related
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.
I'm setting up a python TwitchIO chat bot. The getting started example has this:
async def event_message(self, message):
print(message.content)
await self.handle_commands(message)
#commands.command(name='test')
async def my_command(self, ctx):
await ctx.send(f'Hello {ctx.author.name}!')
If the incoming message is a command (e.g. !test), a message is sent back to the channel with ctx.send().
I'd like the option to send a message back to the channel (based on come criteria) whenever any message is received, not just commands. For example:
async def event_message(self, message):
print(message.content)
if SOMETHING:
SEND_MESSAGE_HERE
await self.handle_commands(message)
I can't figure out how to do some type of .send to make that happen. This answer: TwitchIO: How to send a chat message? show this:
chan = bot.get_channel("channelname")
loop = asyncio.get_event_loop()
loop.create_task(chan.send("Send this message"))
I tried that and the bot sent a ton of messages instantly and got timed out for an hour.
So, the question is: How do you send a message back to the channel inside event_message
A command passes you a Context (an instance of of Messageable, which defines send()). A Channel is also a Messageable, thus it has a send(). So if your Bot instance is bot:
await bot.connected_channels[0].send('...')
Will send a message to the first channel the bot is connected to.
This is the answer I came up with:
bot_account_name = "BOT_ACCOUNT_NAME"
async def event_message(self, message):
print(message.content)
if message.author.name.lower() != bot_account_name.lower():
ws = self._ws
await ws.send_privmsg('CHANNEL_NAME', 'Message To Send')
await self.handle_commands(message)
You can do other checks, but it's important to do the check against the bot account user name. If you don't the bot will see its own messages and reply to them creating a loop. This is one of the issues I ran into where it send a bunch in no time and got timed out by twitch
I found an alternative. I replace the message with a command that I invented for the purpose. The name of the command is "z" but it could have been anything
async def event_message(self, message):
if message.echo:
return
message.content = f"#z {message.content}" # add command name before message
await self.handle_commands(message)
#commands.command()
async def z(self, ctx: commands.Context):
print(f"Original message is {ctx.message.content[3:]}\n")
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)
I want to connect to the telegram's WebSocket or other protocol, to receive every message. I was inspecting the network tab in dev tools, but I could not find any WebSocket protocol, however, when I entered console, I can see [SW] on message {type: "ping", localNotifications: true, lang: {…}, settings: {…}} Which convince me, that it is sent to maintain connection with the WebSocket. I tried a telethon library for python, but it allows me only to show all messages in the chat.
from telethon import TelegramClient
import asyncio
client = TelegramClient(name, api_id, api_hash)
client.start()
for i in client.iter_dialogs():
if i.name == 'test':
chj = i
async def main():
channel = await client.get_entity(chj)
messages = await client.get_messages(channel, limit= None) #pass your own args
#then if you want to get all the messages text
for x in messages:
print(x) #return message.text
"""for i in client.iter_dialogs():
print(i)"""
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
I want to be getting messages like in WebSocket whenever on the desired chat someone's types something
I have found an answer. This can be achieved using events from telethon library
from telethon import TelegramClient, events
name = 'test'
api_id = 1234
api_hash = 'hash'
client = TelegramClient(name, api_id, api_hash)
#client.on(events.NewMessage())
async def newMessageListener(event):
newMessage = event.message.message
print(newMessage)
with client:
client.run_until_disconnected()
I'm making a bot to forward all receiving messages on telegram.
from telethon import TelegramClient
api_id = 12345
api_hash = '0123456789abcdef0123456789abcdef'
client = TelegramClient('anon', api_id, api_hash)
log_channel=-1002030404403
async def main():
async for message in client.iter_messages('me'):
print(message.id, message.text)
if event.is_private:
await client.forward_messages(log_channel, event.message)
with client:
client.loop.run_until_complete(main())
but this is not identifying different of bot and a user
how to filter a bots
event.sender.bot will be True if the sender is a bot.
You can find this in the quick reference for Message, where it says "It bases ChatGetter and SenderGetter.", meaning .sender exists.