Error when sending a message to telegram chat using Python Telethon - python

from telethon import TelegramClient
client = TelegramClient('anon', api_id, api_hash)
async def main():
await client.send_message(chat_id, 'Hello')
with client:
client.loop.run_until_complete(main())
When I try to run the code I get an error:
telethon.errors.rpcerrorlist.ChatIdInvalidError: Invalid object ID for
a chat. Make sure to pass the right types, for instance making sure
that the request is designed for chats (not channels/megagroups) or
otherwise look for a different one more suited\nAn example working
with a megagroup and AddChatUserRequest, it will fail because
megagroups are channels. Use InviteToChannelRequest instead (caused by
SendMessageRequest)
Chat's ID is correct, I checked. What could be the problem?

yes you have to confirm from your chat id and make sure you passed the correct id of your chat. you can use "#_Chat_ID" or use "htttp//t.me/Chat_link"

Related

Wavelink - How do i send message when track has started?

I am currently making a music bot and I don't know how to send a message when track has started. I have tried this, but doesn't work.
async def on_wavelink_track_start(player: wavelink.Player, track: wavelink.Track):
Ctx = player.ctx
AttributeError: 'Player' object has no attribute 'ctx'.
I don't know what to do because the documentation doesn't say anything about this.
Version of llibraries I am using: Wavelink(1.3.5) and Discord.py(2.0).
Player only has guild as an attribute, which isn't enough to send a message.
You can grab a channel object using its id and use that to send your message. The below assumes that your bot client is named client in your code.
async def on_wavelink_track_start(player: wavelink.Player, track: wavelink.Track):
channel = client.get_channel(123456789) # replace with correct channel id
await channel.send('Message to send')
This is only if you want to use the on_wavelink_tract_start event. You could always just send the message from the command that starts the process using ctx like normal.

Python discord bot send message in a channel

I'm trying to run a very simple program: it should check for a string in a link, and in case of a true or false result it should send a different message to a discord channel. The part that verifies the link works, the problem is the part that sends the message, I tried to do it again in different ways but I can't get it to work, this is the code:
#client.command()
async def check_if_live():
global live
contents = requests.get('https://www.twitch.tv/im_marcotv').content.decode('utf-8')
channel = client.get_channel(1005529902528860222)
if 'isLiveBroadcast' in contents:
print('live')
live = True
await channel.send('live')
else:
print('not live')
live = False
await channel.send('not live')
In other parts of the code where I send a message in response to a command using await message.channel.send("message")everything works as expected.
I have done a lot of research but can't find anything useful.
*edit:
With the code above the error is 'NoneType' object has no attribute 'send' on the line await channel.send('not live'), if i try to do as suggested by Artie Vandelay inserting await client.fetch_channel(1005529902528860222) before channel = client.get_channel(1005529902528860222) on the inserted line I have an error 'NoneType' object has no attribute 'request'.
Since I think that at this point it may have a certain value, I also insert the code sections about the client variable.
client = discord.Client()
load_dotenv()
TOKEN = os.getenv('TOKEN')
#all bot code
client.run(TOKEN)
I also tried this:
bot = commands.Bot(command_prefix='!')
load_dotenv()
TOKEN = os.getenv('TOKEN')
#bot.command()
#all bot code
bot.run(TOKEN)
Both methods return errors
Double check if your channel id is correct.
Also try using
.text
instead of
.content.decode('utf-8')
if it still does not work, please send your error message, so we can see what is wrong.
I answer my question because I found a solution, instead of using #bot.command I used #bot.event async def on_ready(), and now it works, I hope this answer can be useful to someone else who has this same problem.

Downloading in real-time 1000s of Telegram chats with Python Telethon?

I have set up a script to download messages from thousands of Telegram supergroups (named chatlist). This works fine when I use a few groups, however, allowing 1000< groups seems to break it and no messages are collected at all. Is this the correct way to approach it, or is there a more efficient way? I don't think it's a network issue my end as I have GB internet
from telethon import TelegramClient, events, sync
client = TelegramClient('test', api_id, api_hash)
#client.on(events.NewMessage(chats=chatlist))
async def my_event_handler(event):
message = event.message.to_dict()
print(message['message'])
await client.start()
await client.run_until_disconnected()
A simple workaround is to remove the NewMessage event filter i.e.:
#client.on(events.NewMessage())
and filter messages inside the method yourself:
async def my_event_handler(event):
message = event.message.to_dict()
input_chat = await event.get_input_chat()
if input_chat in chatlist:
print(message['message'])
You didn't mention what's inside chatlist, so I assumed it's a list of InputChat objects.
Note that if your chat list is a list of #username strings, you'll soon reach Telegram username resolve limits. Always have InputChat or long ids in the chatlist.

Telegram get message by channel ID

I am subscribed to a private telegram Channel/chat where I am not admin and the username is not public.
I can get the channel id from the url in the form https://web.telegram.org/#/im?p=c1234567890_12345678901234567890
And can read all the messages in my telegram and via my web browser.
The channel outputs data (messages) that I want to grab and format and ultimately automatically append to a csv file or such like via a bot or an app on my mac.
Is it possible to do this?
I am currently trying to do this in Python using the Telethon package.
I have been trying to access or address the channel by ID but get errors like
No user has "c1234567890" as username
Or
No user has "-1001234567890" as username
I am trying to use the telethon client.getmessages() method but looks like it will only accept a username and not a chat or channel ID.
Any help/guidance or pointing in the right direction appreciated - I think my main issue is resolving the channel ID to a username or finding classes/methods where I can get the messages by channel ID.
yes, you can used channel ID for search. use it as a int not as a String
this code will help you to understand.
from telethon import TelegramClient
# Remember to use your own values from my.telegram.org!
api_id = 12345
api_hash = '0123456789abcdef0123456789abcdef'
client = TelegramClient('anon', api_id, api_hash)
async def main():
# You can print the message history of any chat:
# chat id is -1001209767229
async for message in client.iter_messages(-1001209767229):
print(message.sender.username, message.text)
with client:
client.loop.run_until_complete(main())

How to get a message from Telegram groups by API?

I was looking for some way to listen and catch new messages provided by telegram groups.
I have not found libraries or API in order to do this in Python.
Someone having any suggestion?
Using Telethon
Replace channel_name with your telegram channel.
from telethon import TelegramClient, events, sync
# Remember to use your own values from my.telegram.org!
api_id = ...
api_hash = '...'
client = TelegramClient('anon', api_id, api_hash)
#client.on(events.NewMessage(chats='channel_name'))
async def my_event_handler(event):
print(event.raw_text)
client.start()
client.run_until_disconnected()
There are two ways to achieve your goal:
Method 1:
My suggested library for python: python-telegram-bot
Create a bot.
Add the bot to the desired group as administrator.
Listen to messages as you normally listen in bots.
Method 2:
My suggested library for python: Telethon
Join the desired group as a user (not a bot).
Create a simple client that listens to new messages.

Categories