How to get new message received from the telegram channel using telethon - python

I used the code given here to receive new message from the user but it does not work when a new message arrives in the telegram channel.
#bot.on(events.NewMessage)
async def my_event_handler(event):
print(event.stringify())
Setting events.NewMessage(chat='chat') or events.NewMessage(chat='channel') didn't work.
How can a telegram bot get new message event from a telegram channel ?

For a bot to receive all messages, you first need to configure it in #BotFather by disabling the bot privacy:
/start
/mybots
(select a bot)
Bot Settings
Group Privacy
Turn off
With that done, add the bot as admin to your broadcast channel (they can't be normal members here). Your code should look like this:
CHANNEL = ... # id, username or invite link of the channel
# the first parameter is the `chats=`, you can use a named argument if you want
#bot.on(events.NewMessage(CHANNEL))
async def my_event_handler(event):
print(event.stringify())
If you want to handle messages from all broadcast channels your group is in, use a more advanced filter:
# megagroups (supergroups) are channels too, so we need `not e.is_group`
# this lambda takes the event, which has these boolean properties
#bot.on(events.NewMessage(func=lambda e: e.is_channel and not e.is_group))
async def my_event_handler(event):
print(event.stringify())

If you only want to get the message text instead of the entire json, you can try this
print(event.message.message)

Related

Getting content from a dm in discord.py

So I want to know if it is possible, that a bot gets the content sent to it in a dm and send that in a specifyed channel on a server.
So basically you dm the bot the word "test" and the bots sends the word in a channel of a server
Yes, it is possible for a bot to receive a direct message and then repost the message in a specified channel on a server. This can be done using the Discord API.
You can do the following:
Create a Discord bot and add it to your server. You can do this using the Discord developer portal.
Use the Discord API to listen for messages sent to the bot in a DM. You can do this using the message event and the DMChannel class in the Discord API.
When the bot receives a DM, use the Discord API to repost the message in the specified channel on the server. You can do this using the send method of the TextChannel class in the Discord API.
Yes, this is possible:
First, we use the on_message() event to detect when a message is sent.
We then check if the message is sent in a DM.
If so, we will send a message to a specific channel.
Here is one way you can implement it:
# import ...
bot = discord.Bot(...)
#bot.event
async def on_message(message):
# check if it's
if isinstance(message.channel, discord.DMChannel):
# get the channel from ID
channel = client.get_channel(CHANNEL_ID) # put channel ID here
await channel.send("test") # whatever you want to send
#bot.event:
async on_message(message):
if message.DMChannel:
# define channel and send message to channel.
You can also refer to DOCS.

The bot don't send message in specific channel

I'm trying to make a partnership command and to do that I need the bot to send a message in a specific channel. This is the code:
bot.command()
async def force(ctx, *, message=None):
channel = bot.get_channel(854633281589084221)
await ctx.channel.send(message)
(Sorry for the bad translation)
In the line of code:
await ctx.channel.send(message)
If I put ctx before channel it works, but it sends the message in the channel in which the command was executed and the programme tells me that the local variable channel isn't used, while if I put it after it no longer tells me that channel isn't used but it does not work
channel already has the value of the channel you want to send the message in.
So, you just need to run await channel.send(message) or await bot.get_channel(<id>).send(message) for your bot to work.
(adding on to #TheSj)
When a command is ran, the bot already replies in that given channel.
If you want to make it so it can only reply in that channel, you can use discord permissions using roles and remove the role from each channel you don't want it in.
Hope this helps and have a great day.:)

Read last messages using Telethon

I'm trying to retrieve last messages (and also latest messages) from a specific channel I'm subscribed to.
I tried the following code:
from telethon import TelegramClient, events, sync
# Remember to use your own values from my.telegram.org!
api_id = 'xxx'
api_hash = 'xxx'
client = TelegramClient('xxx', api_id, api_hash)
#client.on(events.NewMessage(chats='Channel 123'))
async def my_event_handler(event):
print(event.raw_text)
client.start()
client.run_until_disconnected()
For some reason, it's not working as it says "Channel 123" not detected.
What's the proper way to get messages from a specific channel (that I don't own but am subbed to)?
You need to add the channel_id in this line
#client.on(events.NewMessage(chats='channel_id'))
Sometimes, you can use the alias of the channel, but for private channels you can see the channel id opening telegram in the web browser and selected the chat, in the search box where appear the url, in the final of this appear the id like this example:
https://web.telegram.org/k/#-1515693207
This is the id -1515693207
Another method is to use get_entity function to obtain the id, and pass it to the function you want to get the messages.
channel_entity = await client.get_entity(PeerChannel(client.message.to_id.channel_id))
Hope this help you.

How to send welcome message in first text channel discord.py

I've got a pretty decent bot that I'm planning to launch soon. It's called moderator and it's supposed to be the perfect moderator bot so that a server won't need actual moderators anymore. So I want it to send a welcome message when it joins the server, but because all servers have different channel names and channels, I can't get a generic channel name to send the welcome message too.
channel = find(lambda x: x.name == 'general', guild.text_channels)
if channel and channel.permissions_for(guild.me).send_messages:
await channel.send(embed=embedvar)
This is what I have right now and as you can see it finds a channel named general and sends the welcome embed message to the general channel. But since not every server has a general channel, I want to have the bot find the 1st channel where it has permission to send messages. Is there a way to do that?
Thanks!
You can get the first channel of the guild with this way:
channel = client.get_guild(guild id).text_channels[0]
So with this code, you can do something like that:
#client.event
async def on_guild_join(guild):
channel = guild.text_channels[0]
embed = discord.Embed(title=guild.name, description="Hello, I'm here")
await channel.send(embed=embed)

Forwarding posts from a private channel of Telegram

I have a invite link of private channel, and I wanna forwards (or delivery) posts from this channel to me. My desired pseudo code is like below.
def get_channel(bot, update):
message=update.channel_post.text
print(message)
updater = Updater(my_token)
channel_handler = MessageHandler(Filters.text, get_channel,
channel_post_updates=True, invite_link='http://t.me/aa23faba22939bf')
updater.dispatcher.add_handler(channel_handler)
This works well when my bot is in the channel which I created(invite_link is added for my purpose. I don't know where invite_link should be input). But what I want is that my bot forwards posts from channel in which my bot is 'not' included. I prefer python, but any API will be ok. I searched all the google world but have no clues.. Any tips appreciated.
I found a solution with Telethon library. It works for me(http://telethon.readthedocs.io/en/latest/extra/advanced-usage/update-modes.html)
def callback(update):
print('I received', update)
client = TelegramClient('session', api_id, api_hash,
update_workers=1, spawn_read_thread=False)
client.connect()
client.add_event_handler(callback)
client.idle() # ends with Ctrl+C
In callback function you can filter only channel posts or group messages.
If you want to forward message (of any kind) from channel (doesn't matter if it's private or public) to any other chat:
add your bot to channel (notes that, bots are only added as an admin to channel and have admin privileges)
following code (in python) will do the Forwarding:
from telegram import Bot
def forward(update, context):
chat_id = update.effective_chat.id
bot = Bot(token=TOKEN)
bot.forward_message(chat_id = chat_id,
from_chat_id = channel_id,
message_id = (number))
the above code, will forward message from 'from_chat_id' to 'chat_id' (is the user's chat_id which ask the query)
channel_id is just simply the channel's telegram invite link (which start with #)
message_id is the unique number of the message which is in the channel. If you right-click on the message inside the channel, and select 'Copy Post Link' and paste it somewhere, is something like this:
https://t.me/c/123456789/2040
(123456789 is the link of private channel. If this was a public channel, instead of '123456789', there was channel's public address which starts with #)
the message id is: 2040, not the whole.
refrence: https://python-telegram-bot.readthedocs.io/en/stable/telegram.bot.html#telegram.Bot.forward_message

Categories

Resources