How to send message to my channel using telethon - python

I'm trying to make my python script send messages to my private channel but I get this error.
telethon.errors.rpcerrorlist.ChatWriteForbiddenError: You can't write in this chat (caused by SendMessageRequest)
I'm only admin in that channel and here is code what I use for sending messages, when I try to send message to myself it works fine..
from telethon import TelegramClient
from telethon.errors import SessionPasswordNeededError
api_id = 'my api id'
api_hash = 'my api hash'
phone = 'my number'
username = 'my username'
# Create the client and connect
client = TelegramClient(username, api_id, api_hash)
client.start()
print("Client Created")
# Ensure you're authorized
if not client.is_user_authorized():
client.send_code_request(phone)
try:
client.sign_in(phone, input('Enter the code: '))
except SessionPasswordNeededError:
client.sign_in(password=input('Password: '))
async def send_mess(message):
await client.send_message(entity='my channel name', message=message)
while True:
some other code
if last_message != new_message:
with client:
client.loop.run_until_complete(send_mess(message=new_message))
last_message = new_message
Do I need to change something to have admin rights on my script or where is the problem? I'll be glad for every answer. Gimme some good sample code guys :D this is really big problem for me now.

At first test that you can send message to another channel or user. if you can't you must share all the code.
then make sure that account you are using at this case is admin in the channel. it's impossible you getting this error if the account is admin.
also check admin rights and make sure post message is enable.
between, use channel username or channel numeric id instead 'my channel name'. channel numeric id starts with -100 like -1001212229355. you better to use numeric id. to find this just forward one of your channel messages to https://t.me/userinfobot.
await client.send_message(entity='my channel name', message=message)

Related

How to get telegram chat invite link using telethon?

I'm trying to get the invite link of a public channel and a public group.
I tried using the ExportChatInviteRequest function but it raises a ChatAdminRequiredError.
The thing I don't understand is why can I see and get the invite link of a public channel \ group with the telegram app but can't get it with telethon?
I use version 1.26.1:
from telethon.tl.functions.messages import ExportChatInviteRequest
async def main():
chat = await client.get_entity('https://t.me/bestmemes')
invite = await client(ExportChatInviteRequest(chat))
print(invite)
raises:
telethon.errors.rpcerrorlist.ChatAdminRequiredError: Chat admin privileges are required to do that in the specified chat (for example, to send a message in a channel which is not yours), or invalid permissions used for the channel or group (caused by ExportChatInviteRequest)
can someone help me, please?
I can see the invite of the given channel via the telegram app:
I did this:
Create a private chat with a bot or a friend
Retrieve api_id and api_hash from https://my.telegram.org/auth
Login to your telegram account using your phone number
Click "API Development tools"
Fill in your application details
Click on "Create application" at the end
Copy App api_id and App api_hash
from telethon import TelegramClient
from telethon.tl.functions.messages import ExportChatInviteRequest
session = 'Test' # The first-part name of a sqlite3 database - "Test.session"
# Contains user name and password to your Telegram account
# App ID and hash key to identify your Telegram App
api_id = 12345 # Use your own api_id
api_hash = '1234567890ABCDEFGHIJKLMNOPQRSTUV' # Use your own api_hash
# Create a connection to your telegram account using this app
# You will be asksed phone number, password, which will be stored into
# "Test.session" sqlite3 database
client = TelegramClient(session, api_id, api_hash)
async def main():
# Send a hello message to yourself
await client.send_message('me', 'Hello!')
# Send a hello message to a private chat group
await client.send_message('https://t.me/+xxxxxx', 'Hello!')
# Get a specific chat via its primary link
group = await client.get_entity('https://t.me/+xxxxxx')
# Create additional link
invite = await client(ExportChatInviteRequest(group))
print(invite.link) # Print secondary link
with client:
client.loop.run_until_complete(main())
The ExportChatInviteRequest method you are trying to use creates a private chat link. Obviously you can't do this if you're not an administrator
Here is a small code example that gets links to all open chats
async def get_chat_links():
dump = {}
# get all dialogs
for dialog in await client.get_dialogs():
chat = dialog.entity
# if the dialog does not have a title attribute, then it is not a group
if hasattr(chat, 'username') and hasattr(chat, 'title'):
dump[chat.title] = f'https://t.me/{chat.username}'
# for example, let's save everything to a file
with open('dump.json', 'w', encoding='utf-8') as file:
json.dump(dump, file, indent=4)
with client:
client.loop.run_until_complete(get_chat_links())
I would like to add some explanation about hasattr(chat, 'username'). For some chats you will have https://t.me/None. These are just the same closed chats that do not have an open link to join. But the ExportChatInviteRequest function will not work for these chats either, because it CREATES a link, and does not receive it. And if you are not an administrator in this chat you will get an error

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 can I make the server id an arg discord.py

I'm new to python and discord.py so sorry for any confusion. So I'm trying to make a modmail system for my bot however from my understanding there doesn't seem to be a way to get the server id from a dm or like there is, but if the bot is in multiple servers how do I figure out what server to send the message to? My idea was to check the message sent and see if the user sent the id of the server however I don't think I did it very well.
Here's what I currently did and it seems to work fine however just from the looks I know it can't be right.
#commands.Cog.listener()
async def on_message(self,message):
if not message.author.bot:
if isinstance(message.channel,DMChannel):
message_list = message.content.split()
server_id_sent = message_list[0]
for guild in self.client.guilds:
if str(guild.id) == server_id_sent:
message_list.remove(server_id_sent) #I thought by doing this I could remove the id from the message
guild = self.client.get_guild(int(server_id_sent))
print(guild)
modmail_channel = discord.utils.get(guild.channels, name="modmail")
modmail_channel_id = modmail_channel.id
channel = self.client.get_channel(modmail_channel_id)
await channel.send("TEST")
else:
await message.channel.send("Please provide the ID of the server")
By the way, first time using stackoverflow so hopefully I followed the format correctly.
Here's how I would do it:
We're going to set a command for when a user wants to send something to the specified server.
Getting the server name/ID won't actually be useful, as the bot won't know where to send that message. Instead, we will need a channel ID. To make this more user friendly, we're going to set a certain server name with it's channel id (let's just say it could be a log or ticket channel for the bot for these kind of messages)
I set mine like this:
Server: myServer
Server's channel ID: 1234567
Once we got the server name, we will send a message to the corresponding channel ID and send a message to the user that the request has been successfully recieved and made.
#client.event
async def on_message(message):
if message.content.startswith("?request"):
try:
server_name = message.content.split(' ')[1] #this gets the server name the user specified and saves it in a variable
except:
await message.channel.send("Invalid Usage! Syntax: ?request <serverID>")
return
if server_name == "myServer":
channel_id = 1234567
else:
await message.channel.send(f"The server `{server_name}` is not a valid server.")
return
get_channel = client.get_channel(channel_id)
await get_channel.send("Hello!")
#finally we're going to notify the user that his request has been successfully recieved
await message.channel.send(f"Message successfully sent to `{server_name}`!")
I am aware that
if server_name == "myServer":
channel_id = 1234567
is not really an elegant solution. If you want to store multiple servers with their respective logs channels ID's you could just store them in a dict or in a json file. Then access them in this way.
Json file example:
{
"myServer": "1234567",
"mySecondServer": 0987675
}
import json
json_file = open('servers.json').read()
servers = json.loads(json_file)
try:
get_channel_from_server = servers[server_name]
except:
await message.channel.send(f"The server `{server_name}` is not a valid server.")

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())

Telethon: check if client instance is logged in

I am trying to log the user into the account using the telegram bot API, and I can't find a way to check if the client instance has access to an account...
this is my instance:
client = TelegramClient(client_name, API_ID, API_HASH)
by using client.start() it detects if the user is logged in or not, so i must have access to that too...
You need to use get_me(): it will return the current logged in user or None if there isn't one.
client = TelegramClient(client_name, API_ID, API_HASH)
if (await client.get_me()):
# client has an user logged in
else:
# client hasn't an user logged in
Also, if you take a look at the source code, you'll see that start() is doing the same.

Categories