Reactions to messages Telegram/Telethon - telethon

The "telethon" library has a "get messages" method, with which you can get a message and information about it, including comments.
But can you get reactions?
https://core.telegram.org/method/messages.getMessageReactionsList

I couldn't find a way to do this via telethon.
However, you can get a list of reactions to messages using pyrogram: GetMessageReactionsList
Something like that:
from pyrogram import Client
from pyrogram.raw.functions.messages import GetMessageReactionsList
app = Client(
"my_account",
api_id=12345678,
api_hash='XXX'
)
chat_id = -123456789
with app:
peer = app.resolve_peer(chat_id)
for message in app.iter_history(chat_id=chat_id):
reactions = app.send(
GetMessageReactionsList(
peer=peer,
id=message.message_id,
limit=100
)
)
UPD
Found an easier way:
with app:
peer = app.resolve_peer(chat_id)
for message in app.iter_history(chat_id=chat_id):
print(message.reactions)

I recently was looking for reactions as well and discovered the GetMessagesReactionsRequest() function from the Telegram API methods list:
with TelegramClient(session, api_id, api_hash) as client:
reaction = client(GetMessagesReactionsRequest(chat_test, id=[4775]))
Where ID is the message ID. There might be a more efficient solution, as soon as I found it I'll let you know.

In telethon 1.25.4 you can get it easily:
with TelegramClient(session, api_id, api_hash) as client:
for message in client.get_messages('#'+channelusername):
print(message.reactions)

Related

check if a private channel invite link is invalid/expired in telethon

When you try to access a private channel using expired link in telegram client you will get this message
expired link
is there a way to check if a channel invite link is invalid or expired without joining the channel ?
You can use checkChatInvite:
from telethon.sync import TelegramClient
from telethon import functions, types
with TelegramClient(name, api_id, api_hash) as client:
result = client(functions.messages.CheckChatInviteRequest(
hash='A4LmkR23G0IGxBE71zZfo1'
))
print(result.stringify())

cant iterate through members of a server discord API

import discord
import asyncio
from discord.ext import commands
client = commands.Bot(command_prefix=':')
token = ''
#client.event
async def on_ready():
print('BOT ONLINE')
#client.event
async def on_message(message):
channel = message.channel
if message.content.startswith('/'):
if message.content.startswith("/users"):
# FOR LOOP IN QUESTION ---------------
for guild in client.guilds:
for member in guild.members:
print(member) # or do whatever you wish with the member detail
client.run(token)
print("Bot Finished")
When I run this code all it returns is the bot name twice. The server has two members, myself and the bot. I need to iterate through every member of the server. What am I doing wrong?
You simply didn't enable intents.members
intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix=":", intents=intents)
Also make sure to enable them in the developer portal
Reference:
intents.members
How to enable privileged intents

Hey could someone show me some code on a discord.py API? Using an api from a website

Im trying to create a fortnite API to give me all of the Leaked cosmetics with a discord bot and I just don't know where to get started! Could someone help! Thankyou
Here's an example of a simple bot that repeats what you say.
import discord # importing the discord.py library
from discord.ext import commands # extension of said library
# This defines the bot's command prefix and if the commands are case insensitive
bot = commands.Bot(command_prefix='-', case_insensitive='True')
#bot.event =
async def on_ready():
```
This is an event that prints to the console that the bot is online and ready to go.
```
print('Bot is ready!') # prints to console that the bot is ready.
#bot.command()
async def echo(ctx, *, msg):
```
This is a command that repeats what you say. Echo is the name. *, msg means that all the words listed after the command are repeated
```
await ctx.message.delete() # delete the command message the the user said
await ctx.send(msg) # say whatever the user wanted to say.
# bot token here. found in the discord developer website
bot.run(YOUR BOT'S TOKEN GOES HERE)
Here's an example of using a api inside a Cog
Necessary Imports:
from discord.ext import commands
from discord import Embed, Color
from aiohttp import ClientSession
from ast import literal_eval
A command to fetch random Chuck Norris jokes
#commands.command()
async def chuck(self, ctx):
ad = Embed(color=Color.dark_gold())
base = "https://api.chucknorris.io/jokes/random"
async with ClientSession() as session:
data = await get(session, base)
data = literal_eval(data)
ad.set_author(name="Chuck Norris",
icon_url="https://i.ibb.co/swZqcK7/norris.gif",
url=data['url'])
ad.description = data['value']
return await ctx.send(embed=ad)
If you're getting information from Fortnite, chances are they already have a Python Module on PyPi, alternatively you can look for a JSON endpoint and apply what I did above to get what you need.

How to obtain chatid of a private channel by given joinlink using Telegram API?

I have a join link like this: https://t.me/joinchat/AAAAAEI95pT9clShebEcMg
I want to know the functions that leads me to obtain the chatid of that channel.
Thank you.
You may use telegram API function messages.checkChatInvite
from telethon import TelegramClient
from telethon.tl.functions.messages.check_chat_invite import CheckChatInviteRequest
client = TelegramClient('session_id', '+phonenumber', api_id=1234, api_hash='0cxxxxxxx')
client.connect()
channel_hash = "AAAAAxxxxxxxx"
result = client.invoke(CheckChatInviteRequest(channel_hash))
print (result)
and the result would be something like this:
(chatInviteAlready (ID: 0x5abcdefg) = (chat=(channel (ID: 0x5abcdefg) = (creator=None, kicked=None, left=None, editor=True, moderator=None, broadcast=True, verified=None, megagroup=None, restricted=None, democracy=None, signatures=None, min=None, id=123456789, access_hash=615xxxxxxxxx, title=testChannel, username=None, photo=(chatPhotoEmpty (ID: 0x37xxxxxxx) = ()), date=2017-06-14 14:34:50, version=0, restriction_reason=None))))
Here the id in the response is the channel id you are looking for.
The above example is using Telethon and python, but you may use any language and client to connect to telegram API.

How to obtain Telegram chat_id for a specific user?

How to obtain user chat_id in Telegram bot API?
The documentation says:
Integer | Unique identifier for the message recipient — User or GroupChat id
The message updates you receive via getUpdates or your webhook will contain the chat ID for the specific message. It will be contained under the message.chat.id key.
This seems like the only way you are able to retrieve the chat ID. So if you want to write something where the bot initiates the conversation you will probably have to store the chat ID in relation to the user in some sort of key->value store like MemCache or Redis.
I believe their documentation suggests something similar here, https://core.telegram.org/bots#deep-linking-example. You can use deep-linking to initiate a conversation without requiring the user to type a message first.
I created a bot to get User or GroupChat id,
just send the /my_id to telegram bot #get_id_bot.
It does not only work for user chat ID, but also for group chat ID.
To get group chat ID, first you have to add the bot to the group,
then send /my_id in the group.
Here's the link to the bot.
There is a bot that echoes your chat id upon starting a conversation.
Just search for #chatid_echo_bot and tap /start. It will echo your chat id.
Another option is #getidsbot which gives you much more information. This bot also gives information about a forwarded message (from user, to user, chad ids, etc) if you forward the message to the bot.
First, post a message in a chat where your bot is included (channel, group mentioning the bot, or one-to-one chat). Then, just run:
curl https://api.telegram.org/bot<TOKEN>/getUpdates | jq
Feel free to remove the | jq part if your dont have jq installed, it's only useful for pretty printing. You should get something like this:
You can see the chat ID in the returned json object, together with the chat name and associated message.
You can just share the contact with your bot and, via /getUpdates, you get the "contact" object
Using the Perl API you can get it this way: first you send a message to the bot from Telegram, then issue a getUpdates and the chat id must be there:
#!/usr/bin/perl
use Data::Dumper;
use WWW::Telegram::BotAPI;
my $TOKEN = 'blablabla';
my $api = WWW::Telegram::BotAPI->new (
token => $TOKEN
) or die "I can't connect";
my $out = $api->api_request ('getUpdates');
warn Dumper($out);
my $chat_id = $out->{result}->[0]->{message}->{chat}->{id};
print "chat_id=$chat_id\n";
The id should be in chat_id but it may depend of the result, so I also added a dump of the whole result.
You can install the Perl API from https://github.com/Robertof/perl-www-telegram-botapi. It depends on your system but I installed easily running this on my Linux server:
$ sudo cpan WWW::Telegram::BotAPI
Hope this helps
chat_id is nothing but id of user (telegram user account id). You can start a chat with #get_my_chat_id_bot. It will send you back the chat_id (your user_id).
There are following commonly used ids: channel id, group id, bot id, chat id(user id).
Straight out from the documentation:
Suppose the website example.com would like to send notifications to its users via a Telegram bot. Here's what they could do to enable notifications for a user with the ID 123.
Create a bot with a suitable username, e.g. #ExampleComBot
Set up a webhook for incoming messages
Generate a random string of a sufficient length, e.g. $memcache_key = "vCH1vGWJxfSeofSAs0K5PA"
Put the value 123 with the key $memcache_key into Memcache for 3600 seconds (one hour)
Show our user the button https://telegram.me/ExampleComBot?start=vCH1vGWJxfSeofSAs0K5PA
Configure the webhook processor to query Memcached with the parameter that is passed in incoming messages beginning with /start. If the key exists, record the chat_id passed to the webhook as telegram_chat_id for the user 123. Remove the key from Memcache.
Now when we want to send a notification to the user 123, check if they have the field telegram_chat_id. If yes, use the sendMessage method in the Bot API to send them a message in Telegram.
Whenever user communicate with bot it send information like below:
$response = {
"update_id":640046715,
"message":{
"message_id":1665,
"from":{"id":108177xxxx,"is_bot":false,"first_name":"Suresh","last_name":"Kamrushi","language_code":"en"},
"chat":{"id":108xxxxxx,"first_name":"Suresh","last_name":"Kamrushi","type":"private"},
"date":1604381276,
"text":"1"
}
}
So you can access chat it like:
$update["message"]["chat"]["id"]
Assuming you are using PHP.
Extending #Roberto Santalla answer and if you prefer to use Telegram API together with javascript and axios library then you might want the following:
const method = 'get'
const headers: any = {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json',
timestamp: +new Date(),
}
const options = { headers: { ...headers } }
const urlTelegramBase =
'https://api.telegram.org/bot123456:ABCDEF'
const urlGetUpdates = `${urlTelegramBase}/getUpdates`
const username = 'user_name'
const {
data: { result: messages },
} = await axios[method](urlGetUpdates, options)
const chat_id = messages.find(
messageBlock => messageBlock.message.chat.username === username
).message.chat.id
console.info('chat_id': chat_id)