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
Related
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.
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.
I'm creating a simple Twitch bot for personal use. I'm using twitchio.ext commands. Everything works fine, I'm connected, I'm able to print all the messages from the chat, my bot responds to commands but I'm not able to send a message to chat and I don't know why.
from twitchio.ext import commands
class Bot(commands.Bot):
def __init__(self):
super().__init__(token='oauth:censored', prefix='g ', nick = "nick of the bot", irc_token = "censored", initial_channels=['channel'])
async def event_ready(self):
print(f'Using bot as {self.nick}')
#commands.command()
async def test(self, ctx: commands.Context):
await ctx.send('test')
print("printed")
bot = Bot()
#bot.event()
async def event_message(msg):
print(msg.author.name)
print(msg.content)
await bot.handle_commands(msg)
bot.run()
When I type "g test" in chat, the message "test" is not sent but the message "printed" is printed to the console. Do you know where could be the problem? Also, I would like to ask if there is any way how to send a message to chat directly without responding to a command or event.
Try adding the bot as a mod
The 'nick' in the bot init() function doesn't seem to do anything the nick is linked to your IRC username.
I'm assuming the channel in your initial_channels in the init() func isn't actually the channel you put there since you said you were able to type in the chat.
If the channel that you are using the bot from(linked to the oauth key) is not the same channel as you are connecting to in the chat then you probably need to add the bots username as a moderator in that chat
try
/mod [bot_username]
in the chat as the channel owner to do this
Also if your bot is the same account you are sending commands from on twitch the rate limit will be reached unless they are a mod. So either make a dedicated account for your bot or mod the bot on the server
Hi can't figure out how to solve this problem, so any help will be really appreciated.
I'm subscribed to a private channel. This channel has no username and I don't have the invite link (the admin just added me).
Since I use this channel at work, to speed up the things I want to process the messages posted on the channel using Telethon.
The core of the program is:
#events.register(events.NewMessage(chats = my_private_channel))
async def handler(event):
#do things
The problem is that I am not able to filter the messages coming to that specific channel id. I get the error:
ValueError: Cannot find any entity corresponding to "0123456789"
I have tried different technique to obtain my channel Id but the error is always the same. In particular:
The channel is private so it has no username ("#blablabla")
I have no invite link
I have tried to process all incoming messages until the admin sent a message on the channel, print sender information and get the value from the "ID" key
I have tried to use telegram web and get the ID from the url (also adding -100 in front of it)
But when I put the ID in the parameter chats, I get always the error reported above.
Thanks in advance,
Have a nice day
if you have access to the channel, then it's shown in your chat list.
You have to loop through your chats checking their titles and then store the desired chat in a variable:
my_private_channel_id = None
my_private_channel = None
async for dialog in tg.client.iter_dialogs():
if dialog.name == "private chat name":
my_private_channel = dialog
my_private_channel_id = dialog.id
break
if my_private_channel is None:
print("chat not found")
else:
print("chat id is", my_private_channel_id)
Than you can filter messages sent to my_private_channel.
You can print all the dialogs/conversations that you are part of.
also you need to remove -100 prefix from the id you got like: -1001419092328 = 1419092328 (actual ID)
from telethon import TelegramClient, events
client = TelegramClient("bot", API_ID, API_HASH)
client.start()
print("🎉 Connected")
#client.on(events.NewMessage())
async def my_event_handler(event):
async for dialog in client.iter_dialogs():
print(dialog.name, 'has ID', dialog.id) # test ID -1001419092328
client.run_until_disconnected()
if you want to listen to a specific channel, you can use channel_id=1419092328. you will only receive messages that are broadcasted to it:
from telethon import TelegramClient, events
from telethon.tl.types import PeerChannel
print(f"👉 Connecting...")
client = TelegramClient("bot", API_ID, API_HASH)
client.start()
print("🎉 Connected")
#client.on(events.NewMessage(PeerChannel(channel_id=1419092328)))
async def my_event_handler(event):
msg = event.text
print(f"[M] {msg}")
client.run_until_disconnected()
You can't join a private channel without the invite link, nor can you get any information about it. It's private, as the name implies.
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)