Telegram retrieving groupname by user id - python

I'm using telethon GetFullUserRequest to retrieve user id and name.
I want to see if this user id is a member of a group, or even a member of multiple groups.
I googled but I can't find a solution.
Is this possible, and if yes, how?
Regards and thanks in advance.

As #go2nirvana pointed out, you can get the common chats, but that's all you can do (there is simply no way to know which broadcast channels they're in, or what groups unless you're in them too).
This is done with GetCommonChatsRequest and is what clients show as "groups in common" when you open someone's profile:
async def main():
result = await client(functions.messages.GetCommonChatsRequest(
user_id='username',
max_id=0,
limit=100
))
for chat in result.chats:
...

Related

Discord.py Automatically assign roles to users having specific keywords in a message or image

I'm extremely new to discord.py and I was wondering if there is an existing bot or if I could make a bot that can assign a role to a user based on keywords in a text and/or image to get a specific role through verification.
Is this possible and if so can I get some help with it?
I have tried looking for bots that may have this feature but I have been unsuccessful, I am somewhat willing to make a bot as well but I'm a beginner coder but I am willing to figure things out!
It is possible. But I'm unsure when you want this to be triggered;
checking every possible message?
messages in a certain channel?
some kind of response to a slash command/modal dialog?
etc
Let's role with "checking every possible message" for a basic example.
Let's say we have a server about people's favourite fruit and we want to assign users a role based on their favourite fruit as this gives them access to the private channel about that fruit.
import discord
# we have already created roles in our server for the fruits
# so we'll put the IDs here for ease of use
ROLES = {
"banana": 112233445566,
"apple": 123456123456,
"orange": 665544332211
}
# requires elevated privileges - but let's say we've ticked those
intents = discord.Intents.all()
client = discord.Bot(intents=intents)
# register a client event to trigger some code every time a message is sent
#client.event
async def on_message(message: discord.Message):
message_content = message.content.lower()
if "bananas are good" in message_content:
role = ROLES["banana"]
elif "apples are good" in message_content:
role = ROLES["apple"]
elif "oranges are good" in message_content:
role = ROLES["orange"]
else:
# make sure we have a case for when nothing we want is found
role = None
if not role:
# exit out if we don't have a role to assign
return
guild_roles = await message.guild.fetch_roles()
our_role = [gr for gr in guild_roles if gr.id == role]
await message.author.add_roles(our_role)
client.run(OUR_TOKEN)
This is a very basic example but it possible. Ideally, we'd have a better way of checking message content - either via regex or other form of analysis. Additionally, we'd probably only check messages in a certain channel (or another method entirely, like a modal dialogue or a slash command). Also, what we're not doing above, is removing the user from the other roles (provided you would want that). So it would be possible for a user to have the "banana", "oranges", and "apples" roles all at once.
Hopefully that gives some ideas of where to start. Images would be similar - triggering some kind of function when you want it, downloading the image and running whatever analysis you want on the image.
Disclaimer: I wrote this with the pycord library in mind and didn't see the discord.py tag - should mostly be similar though but might not be.

How to delete a private chat (pyrogram)

i tried pyrogram.raw.functions.messages.DeleteChat but get following trackback
pyrogram.errors.exceptions.bad_request_400.PeerIdInvalid: Telegram says: [400 PEER_ID_INVALID] - The peer id being used is invalid or not known yet. Make sure you meet the peer before interacting with it (caused by "messages.DeleteChat")
account.UpdateNotifySettings has the same problem too.
await client.invoke(UpdateNotifySettings(peer=await client.resolve_peer(cid),settings=InputPeerNotifySettings(silent=True)))
i have read this doc and i am sure that the id is correct for client.archive_chats works well with the same id.
the id is like this 5126101582 is there any another kinds of id or my code is wrong
note:
what i need is like this:
UPDATE
Ok, I THINK I've found a solution for personal chats too!
I was messing around with something else and reading this part of the documentation, I have come up with a way of listing every conversation and their respective id:
from pyrogram import Client
app = Client("my_client")
async def main():
async with app:
async for dialog in app.get_dialogs():
print(str(dialog.chat.id) + " - " + str(dialog.chat.first_name or str(dialog.chat.title)) )
app.run(main())
Basically what it does is loop through all your chats and output their id and "title" in case of a group/channel and a name in case of a chat with a person. You will notice that some ids will be output with a hyphen (-) in front of them, and some won't.
You will need to copy that exact string with or without the hyphen and then you can do this to delete all messages from a chat:
from pyrogram import Client
app = Client("Telecom")
async def main():
await app.start()
async for message in app.get_chat_history("1212345678"):
await app.delete_messages("1212345678", message.id)
app.run(main())
--------------------------- END OF UPDATE ------------------------
I could not understand clearly if you want to delete only the messages of a specific chat or if you want to delete the chat per se.
Anyways, here's what the documentation says:
chat_id (int | str) – Unique identifier (int) or username (str) of the target chat. For your personal cloud (Saved Messages) you can simply use “me” or “self”. For a contact that exists in your Telegram address book you can use his phone number (str).
Reference:
Pyrogram Documentation - Delete Messages
Therefore, you cannot delete messages from a chat with the ID, unless it's a channel/bot/group - and since you're receiving this error, I'm assuming you want to delete a chat with a person.
Now, if you are trying to delete, let's say, messages with a channel, there are several ways to retrieve the right ID.
The one I use the most is going to web.telegram and changing it to the "legacy" version.
Once there, click on the chat id you want to delete messages with. You should see something like this:
Telegram URL
you will need the numbers after the "c", and before the underscore.
So let's say my number is c1503123456789_1111111111111
You will use 1503123456789.
You also need to add -100 to it. So the final number will be:
-1001503123456789.
I hope that helps somehow.
Good luck!
you can delete a dialog with leave_chat method.
Leave chat or channel
await app.leave_chat(chat_id)
Leave basic chat and also delete the dialog
await app.leave_chat(chat_id, delete=True)
Bound method leave of Chat.
Use as a shortcut for:
await client.leave_chat(123456789)
Example
await chat.leave()
fine
await client.invoke(DeleteHistory(max_id=0, peer=await client.resolve_peer(cid))
works

"ValueError: Could not find the input entity for PeerChannel" with Bot

For the life of me, I can't figure out this one out.
I have created a new Telegram Bot and created a new channel, in which I added my bot as an Admin.
After reading 100 times the docs, I tried to have the entity "seen" somehow but :
get_dialogs() is not allowed for bots
client.get_entity('') is not allowed for bots
Not sure what else to do…
I do have published some messages in the channel.
My code looks something like :
from telethon import TelegramClient
telethon_client = TelegramClient(
api_id=int(config['TELETHON_API_ID']),
api_hash=config['TELETHON_API_HASH'],
session=config['TELETHON_SESSION']
).start(bot_token=config['TELEGRAM_BOT_TOKEN'])
with telethon_client:
telethon_client.loop.run_until_complete(__async_get_users(chat_id))
async def __async_get_users(chat_id):
channel = await telethon_client.get_entity(chat_id) # -100xxxxx
tg_users = await telethon_client.get_participants(channel)
Any help, lead, or idea appreciated !
Ok, so, not sure what lead to the resolution of this issue but I did :
disable group privacy mode in #BotFather as #Lonami advised
Sent other messages in the group
Removed and re-added the bot to the group
I still had the issue, but after clearing the session, it now works OK!
Thanks #Lonami for the help!

How would I change a voice channel's bitrate using discord.py?

I have a voice channel that I would like to change the bitrate of, but I can't find any ways of doing it in the docs. How would I do it?
Edit:
I've figured it out, you have to fetch the channel from id and change it from there.
vchannel = await self.fetch_channel(id)
await vchannel.edit(bitrate=96000)
I advise you to use client.get_channel instead of client.fetch_channel because it's not an API call so you won't be ratelimited, and it will be faster.
The second problem in your code is that you used self, good, but you didn't put client (or bot, depdending of what you set) after it.
For me your code must be :
vchannel = self.client.get_channel(id)
await vchannel.edit(bitrate=96000)
Have a nice day!

how do you mention

I need to mention a specific role with the id 631147065925173310. I have tried everything and a lot of people said to me that I don't know python, which is hard, but I am learning how to use discord.py for only 2 days.
if channel.name == "General":
await ctx.send(f"{ctx.author.mention}needs help at{channel.mention})
else:
await ctx.send(f"{ctx.author}needs help at an unknown place")
I want that whenever a person write 'h!' or help, it will say:
#user needs help at #channel #specific role
You can try
user = self.bot.get_user(ctx.author.id)
role = ctx.guild.get_role(631147065925173310)
await ctx.send(f"{user.mention} needs help in {ctx.channel.mention}, please attend {role.mention}")
If you are using this in a cog use my code and if you are using bot for commands.
If you are using this in the main command use bot.get_user(ctx.author.id) instead of what I have.
To mention a role or user you should use this syntax in your message:
<#id>
So change "id" for the id of the respective role, so your code would be:
awit ctx.send(f"<#{userId}>nedds help at<#{channelId}>)

Categories