How to delete a private chat (pyrogram) - python

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

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 forward message from a specific chat in Telethon?

This is a continuation of this short forum (How forward message to other contact with telethon).
Problem
I replaced entity with the group id for GC A and it works since I type something in GC B the bot forwards it to GC A however, when I message GC A the bot still forwards the messages to GC A which I don't want, I just want it to not react.
await client.forward_messages(entity, event.message)
The bot forwards every new message because the event type is new messages so I was thinking, is there a way to filter it so that it only triggers when there are new messages on a specific group?
#client.on(events.NewMessage)
async def main(event):
Solutions Ive tried
Looking at the documentation (https://docs.telethon.dev/en/latest/modules/client.html#telethon.client.messages.MessageMethods.forward_messages) there is an example with the argument "from_chat". So I placed the group id of GC B but it doesn't work.
await client.forward_messages(chat, message_id, from_chat)
I also tried making the argument look like this to copy the examples better but It does not work
await client.forward_messages(entity("group ID"), event.message, from_chat("group_id"))
For me worked this code:
#client.on(events.NewMessage(chats = FROM_CHANNEL_ID))
async def main(event):
await event.forward_to(TO_CHAT_ID)
Try it, may it will work for you to.

"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!

discord py - message.mentions "else" makes nothing

I want to get the user that was mentioned in a message and send him a private message. That's working without problems, but now I want to add a message for the case, that the mentioned member is not on the same server.
I searched a lot and try now for over 3 hours to find a solution.
Showcase of the problem: https://youtu.be/PYZMVXYtxpE
Heres my code:
#bot.event
async def on_message(message):
if len(message.mentions) == 1:
membe1 = message.mentions[0].id
membe2 = bot.get_user(membe1)
guild = bot.get_guild(message.author.guild.id)
if guild.get_member(membe1) is not None:
await membe2.send(content=f"you was mentioned in the server chat")
else:
embed2 = discord.Embed(title=f"» :warning: | PING not possible", description=f"not possible")
await message.channel.send(content=f"{message.author.mention}", embed=embed)
await message.delete()
return
The first part is working without problems, but at the "else" part, does the bot nothing. He still posts the message with the "invalid" ping in the chat and just ignores it. What can I do to fix that?
There is an error of design in what you are trying to do.
In Discord, you are not able to mention a user if he is not on that same server, so what you are checking will never work at all, currently your code is pretty much checking if the mentioned user exists, which will always happen unless he leaves the guild at the same time the command is executed.
Say for example, to make your command work you want to mention the user user123, who is in your server, you do the following:
#user123 blablabla
And that works because Discord internal cache can find user123 in your server and it is mentioned, which means that clicking on "#user123" will show us a target with his avatar, his roles or whatsoever.
But if you try to do the same for an invalid user, let's say notuser321:
#notuser321 blablabla
This is not a mention, take for example that you know who notuser321 is but he is in the same server as the bot is. Discord cannot retrieve this user from the cache and it is not considered a mention, just a single string, so not a single part of your code will be triggered, because len(message.mentions) will be 0.
Something that you could try would be using regular expressions to find an attempt to tag within message.content. An example would be something like this:
import re
message = "I love #user1 and #user2"
mention_attempt = re.findall(r'[#]\S*', message) # ['#user1', '#user2']

Telegram retrieving groupname by user id

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:
...

Categories