check if a private channel invite link is invalid/expired in telethon - 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())

Related

How can I convert Telegram Session String from Telegram Session file

I'm trying to get the Session String from an existing Session File of Pyrogram. How can I do that?
Can you help me?
from dotenv import dotenv_values
from pyrogram import Client
config = dotenv_values(dotenv_path='./.env')
app = Client(
# name="withstring",
name="my_bot",
# api_id=config.get("API_ID"),
# api_hash=config.get("API_HASH"),
bot_token=config.get("BOT_TOKEN"),
)
with app:
app.send_message("username", text="Hello world Minhaz!")
s = app.export_session_string()
# print(s)
app.run()
The Session File is an sqlite database storing your authorization against the API and peers you've met (messages received, chats joined, etc).
To get the Session String to authenticate in Memory (losing peers when you log in again), you can just call the Client.export_session_string() method.
Edit to add: If you already have a session file, you can use its name to log in, instead of creating a new in-memory session. If you have a my_account.session file, use Client("my_session") when instantiating your Client.
from pyrogram import Client
app = Client(":memory:")
with app:
session = app.export_session_string()
print(session)

Import Telethon Session AWS Lambda

I am trying to use Telethon with AWS Lambda. More precisely I am trying get messages from some public channels using client object.
Is there a way to import an existing session in AWS Lambda, in order to prevent Telegram/telethon to ask for a validation code (which is not possible to input) ?
Here is the code I am using to try to connect to telegram through telethon in AWS Lambda :
api_id== os.environ.get('TELEGRAM_API_ID')
api_hash = os.environ.get('TELEGRAM_API_HASH')
userName = os.environ.get('TELEGRAM_USERNAME')
phone = os.environ.get('TELEGRAM_PHONE')
os.chdir("/tmp")
client = TelegramClient(userName, api_id, api_hash)
Here is the session file I have imported in AWS Lambda through Layers (same name as userName) session file
But it seems the session file is not used/read as telethon is asking the verification code and phone number.
Anyone know how to fix this ? Thanks
It took some time, but I found a solution to this problem and ran a Telegram client on Lambda)
All you need to do is use a different session type, namely StringSession.
As indicated in the official documentation, all you need to do is generate a StringSession in your local environment, save the string in a file or local variables and use it in your lambda code.
Generate StringSession, you will see the output in your terminal in this case:
from telethon.sync import TelegramClient
from telethon.sessions import StringSession
with TelegramClient(StringSession(), api_id, api_hash) as client:
print(client.session.save())
Save your newly created StringSession into environment variables in Lambda, as described here and now you can do something like this:
from telethon.sync import TelegramClient
from telethon.sessions import StringSession
import os
string = os.environ.get('session') # env variable named "session"
with TelegramClient(StringSession(string), api_id, api_hash) as client:
client.loop.run_until_complete(client.send_message('me', 'Hi'))

Reactions to messages Telegram/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)

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

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.