Get last message/s from Telegram channel with Python - python

I'm using the python-telegram-bot library to write a bot in Python that sends URLs into a channel where the bot is administrator.
Now, I would like to have the bot reading, let's say, the last 5 messages (I don't really care about the number as I just need to read the message on the chat) and store them into a list in the code for further elaborations.
I already have my bot working with:
bot = telegram.Bot(token='mytoken')
bot.sendMessage(chat_id='#mychatid', text=entry.link)
But I can't find a bot.getLastMessage or bot.getMessage kind of class into the python-telegram-bot library.
In case there's already no written class that does that, how can I implement it via the Telegram API as I'm a bit of a beginner when it comes to API implementation?
Thanks.

That's not possible in Bots unfortunately.
Here you can find all available methods (that python-telegram-bot invokes behind the scenes) and there's no such method available to fetch messages on demand.
The closest you can get through the api is getChat (which would return the pinned_message in that chat).
What you can do in this case is, store the messages the bot sends as well as the message updates the bot receives (by setting up a handler) in some storage (database) and fetch from there later on.

Have you tried the other type of Telegram API, Telegram [client] API and TDLib?
Using telethon library makes it easy to read channels history (see telethon docs).
For this, we need an api_id and an api_hash.
To get these parameters, we need to log in to our Telegram core
and go to the API development tools area.
There is a simple form that needs to be filled out, after which, we can receive our api_id and api_hash. See Telegram's help documentation about how to get your API credentials.
Here is an example code that gets the last 5 messages of targetChannelId:
from telethon import TelegramClient
API_ID = 123456 # See above for how to get it
API_HASH = '123abc' # See above for how to get it
client = TelegramClient('my-client', API_ID, API_HASH)
async def main():
async for message in client.iter_messages('targetChannelId', limit=5):
print(message.id, message.text)
with client:
client.loop.run_until_complete(main())
The first time you run this code it asks your phone number or bot token. Enter your phone number in the format +9912345... where 99 is your country code and the rest is your phone number.
It then may send a login code to your Telegram app; enter it in the console.
Note: Bots cannot see channel history messages (at least in telethon) but users (phone numbers) can. Bots can only listen for channel updates only if they are one of its administrators.
The client.iter_messages() accepts other parameters like min_id which can be used so we get messages only after a specific message (for example, we can save the last message id that we have processed and next time pass that id as min_id so only messages after that message are returned).

Related

How can I monitor (test) and view the DMs my Slack Bot is sending?

I've created a slack bot that sends out a private message via the client.chat_postMessage method to different users in my workspace.
They've received the message (they showed me screenshots), however, I cannot see their private conversation via Slack it seems. Is there another way to monitor that the message has arrived and looks the way it's supposed to be (the format, attachments, etc. sent together)?
I tried this method:
response = client.conversations_info(
channel=,
include_num_members=1
)
but when I input the user's channel it returns that the channel doesn't exist.
Here's what my bot's message looks like in Slack according to the receiver. I cannot view it anywhere it seems.
If you're using your bot token to send a message to a user, the message will show up in a DM between your bot and that particular user. Your bot is its own user, separate from your user. For that reason, if you login to Slack, you won't be able to view that conversation as you yourself are not a part of the conversation.
The only way to "view" a message that has been sent to a user within a DM is to call the conversations.history method. Use the channel ID of the DM between the bot and your user, which will start with "D".
If you want to confirm how a message will look like within Slack, send the message to yourself beforehand. Additionally, adding logging within your code will help for any troubleshooting that you may need in the future.

How to use parse mode in telegram send message bot in Python

I'm pretty new to making bot thing so I have several questions I want to ask regarding this:
I'm using a bot to send message by
def send_message(chat_id, msg):
url = f"https://api.telegram.org/bot{bot_token}/sendMessage?chat_id={chat_id}&text={msg}"
requests.get(url)
send_message(chat_id,msg)
By this, I can send message and I want to beautify the result by using parse_mode but I don't know where to put in in url to make it work.
I'm alternate to using Telethon. I can use it to send message to individual and group by user name and group invite link, but when I try to send it to channel by:
client.send_message(entity='my channel name', message=message)
When I try to run it, it return Cannot find any entity corresponding to "Test channel".
I also try
destination_channel_username='test_ali3'
entity=client.get_entity(destination_channel_username)
client.send_message(entity=entity,message="Hi")
but it require my channel access_hash, how can get it, or are there any other way to send message to channel.
I know Telegram bot API have function like sendMessage or bot.sendMessage that also can do the job, but somehow I can't call it, which packages should I install and/or import.
Thanks a lot!
This should do the trick:
def send_message(chat_id, msg, parse_mode):
url = f"https://api.telegram.org/bot{bot_token}/sendMessage?chat_id={chat_id}&text={msg}&parse_mode={parse_mode}"
requests.get(url)
TBH I'm not too familiar with telethon, but that library is mainly intended for so called userbots. that means that it uses the API that also the Telegram app uses and because of that, it's often times more involved than just the plain bot api.
To use the Bot API in Python, I can recommend the package python-telegram-bot, see https://python-telegram-bot.org. Disclaimer: I'm currently the maintainer of that package. There are also other python packages for the bot api, see e.g. https://core.telegram.org/bots/samples#python

discord.py listen for and send private message

I am trying to make a discord bot in Python that listens for private messages and then replies.
The way I want it to be designed is that the user sends a command to the bot "!token", the bot then iterates over an Array. And if the discordID of the message sender is in the list, the bot then returns a token related to that discordID. If the discordID is not there then it replies with "No token".
Quite new to Python. I have looked through documentations and cant seem to find what I am looking for.
Thanks in advance!
As you said that you're new to discord.py and Python in general I've written out a bit more than I generally would without an example of what you've tried yourself.
The way this is set up now it'll only listen to "!token" You can take this code and add your own commands to it by following the same schematic. I've also left the part where you store the tokens out because you weren't clear on how you wanted that. I'd read up on python dictionaries to store those though.
As Patrick Haughs mentioned you can use the check commands.dm_only to make sure this will only run in private messages and not in any servers your bot might connect to.
from discord.ext import commands
idList =[IDS]
bot = commands.Bot(command_prefix = "!")
runtoken = TOKEN
#bot.command()
async def token(ctx):
if ctx.author.id in idList:
await ctx.author.send("Token")
else:
await ctx.author.send("No token")
bot.run(runtoken)

Using the Slack API, how can I direct message all users at the same time?

On Slack, I'm aware that using chat.postMessage allows me to message each user individually, but how would I go about direct messaging the entire team (400 members) at once?
There is no "bulk" variant of chat.postMessage. So you basically need to build your own bulk message sender, which you can easily do by iterating through the list of users and sending each of them a message.
You can get the list of all users with users.list. You then have two option for sending direct messages:
Slackbot channel: Send each of them a message with chat.postMessage using the ID of each user as channel.
App channel: Get the IM channel ID with im.open for each user
and then use that as channel for chat.postMessage. This only works though if you have a bot user and send the message from the bot user.
Keep in mind though, that there is a request limit of 1 message per second.
There also is a 3 seconds request time-out for many requests between Slack and your app. (e.g. for direct response to slash commands). So if your bot needs to send many messages you want to use an approach that allows you to send them asynchronously.
One solution to this problem that works very well for me is to use a messaging queue for all Slack messages sent from my bots.
Hello For that you need a channel with all 400 of them in it, cause currently you cannot send to 400 individual users. For sending message to a channel, you just need to add channel argument for postMessage method.
Check this :: https://api.slack.com/methods/chat.postMessage

Cannot "send_message" in Telegram Bot API

In my own library I'm trying to send a message using "sendMessage" API method from Telegram Bot API. I've create a channel titled, say, "my_channel123" and my user name is "my_username123". So I'm an admin of the channel and the only user.
When I'm trying to send a message to the whole channel or myself from a bot, I get an error Bad request 400. Here's how I'm trying to do that:
my_bot.send_message(chat_id="#my_channel123", text="tetfdsfd")
# or
my_bot.send_message(chat_id="#my_channel123my_username123", text= "tetfdsfd")
# or
my_bot.send_message(chat_id="#my_username123", text="tetfdsfd")
I believe the error is somewhere in the format of the ids of the channel or user name or both. Are all these 3 calls correct, meaning is the format I use for chat_id correct?
Note that most likely the probable case is the id of the chat or user_name (or rather, the format) or something else because other post and get methods in my library work properly.
You have to add the bot to be an administrator of the channel before it can send messages to the channel. After you do that, your first line should work:
my_bot.send_message(chat_id="#my_channel123", text="tetfdsfd")
Also remember that whatever follows the # should be the channel username, not the title.
when sending a message to a channel, i think its easiest to send it with the channel id...
there are a few ways to get the channel id
if the bot is a admin in the channel (go to "add admin..." and search for your bot to add it), then any message sent in the channel, the bot would be able to see it, and in every message there is an id of the sender, if its in a channel, its the channel id...
use this bot #ChannelIdBot... though the bot will still need to be in the channel as an admin, in order to send messages...

Categories

Resources