I'm trying to change the rights of group members/administrators according to the example in the telethon documentation:
https://telethonn.readthedocs.io/en/latest/extra/examples/chats-and-channels.html#admin-permissions,
But the problem is that the required ChannelAdminRights class simply does not exist and I get an ImportError error: cannot import name 'ChannelAdminRights' from 'telethon.tl.types'
How do I change my member rights? (I use Google Translate)
This might help you:
https://docs.telethon.dev/en/latest/modules/client.html?highlight=restrict#telethon.client.chats.ChatMethods.edit_permissions
Here's the code:
from telethon.sync import TelegramClient
import telethon
from datetime import timedelta
api_id = 12345
api_hash = "dddddd"
with TelegramClient("anon", api_id, api_hash) as client:
client.start()
client.connect()
chat_id = client.get_entity("username / chat_id / Title").id
users = client.get_participants(chat_id)
client.edit_permissions(chat_id, users[3], timedelta(minutes = 60), send_messages = False)
With this code, a bot/userbot will mute for one hour an user.
Yeah, that's exactly what I need! I just ran this code and faced with the problem that this method works only for channels and megpgroup, and I have a chat...
Error text:
raise ValueError('You must pass either a channel or a supergroup')
ValueError: You must pass either a channel or a supergroup
Related
hi and thanks for your answer. i want to create a bot for forward message to my channel and delete the last message every 1 minute
i made that but i have some problem for removing the last message. i cant get the last message id from my channel to the bot.
my source is:
from telegram.bot import Bot
from telegram.update import Update
from telegram.ext.updater import Updater
from telegram.ext.callbackcontext import CallbackContext
from telegram.ext.messagehandler import MessageHandler
from telegram.ext.filters import Filters
from telegram.chataction import ChatAction
from time import sleep
import telegram_send
import socket
import telegram
import json
api_key="My API Key"
user_id = "My User Id"
updater = Updater(api_key, use_context=True)
bot = telegram.Bot(token=api_key)
def echo(update: Update, context: CallbackContext):
context.bot.send_chat_action(chat_id=update.effective_chat.id, action=ChatAction.TYPING)
sleep(60)
if update.message['photo'] == []:
bot.send_message(chat_id=user_id, text=update.message.text)
else:
fileID = update.message['photo'][-1]['file_id']
context.bot.sendPhoto(chat_id = user_id,caption=update.message['caption'],photo = fileID)
msg_id = update.message._id_attrs[]
#------------- And Also i user that too -------------
#msg_id=update.message.message_id
#------------- -------------
context.bot.delete_message(chat_id=user_id, message_id=msg_id)
update.effective_chat
update.effective_user
update.effective_message
print(json.dumps(update.to_dict(), indent=2))
dp = updater.dispatcher
dp.add_handler(MessageHandler(Filters.document | Filters.photo, echo))
dp.add_handler(MessageHandler(Filters.text, echo))
updater.start_polling()
and when i use that code this error will show:
The message_id that you want to remove is not exist....
actually i type a message id in manually for delete message and it was work
but i want to delete that message auto
please help me to do that. thanks
I fixed That With Python-Telegram-Bot Version 20
Read This Docs:
https://docs.python-telegram-bot.org/en/v20.0a2/
import asyncio
from pyrogram import Client
from pyrogram.errors import PeerFlood
import time
api_id = 12905662
api_hash = "a7cfcd44cb95d26d7529d547c9a1d9ef"
vubor = input('Напишите "1" для парсинга, "2" для рассылки! ')
text = input('Текст для рассылки: ')
account = ['my_accont1', 'my_accont2', 'my_accont3', 'my_accont4', 'my_accont5', 'my_accont6', 'my_accont7',
'my_accont8', 'my_accont9']
async def main():
if vubor == '1':
user = []
with open('username.txt', 'r') as file:
for users in file.readlines():
y = users.strip()
user.append(y)
for acc in account:
try:
async with Client(f"{acc}", api_id, api_hash) as app:
for all_user in user[0:500]:
time.sleep(5)
await app.send_message(all_user, text)
user.remove(all_user)
except PeerFlood:
print('Аккаунт заблокировн')
asyncio.run(main())
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
Firstly, please learn how to ask a good question.
Secondly, your error message is already clear, you have to
Make sure you meet the peer before interacting with it
This means your session has to receive a message from them directly or via a shared chat, or have your session see any update to do with them in general.
I wrote a script for the documentation of pyrogram for parsing messages in public chats, but it either gives me an error, or does not give anything at all, here is the code:
from pyrogram import Client
api_id = 272347
api_hash = '235ausfhi...'
gruppa = 'xxx'
with Client('sessia1', api_id, api_hash) as app:
spis_mas = []
for message in app.iter_history(gruppa):
spis_mas.append(message.text)
with open('spis_of_mes.txt', 'w') as file:
for mem in spis_mas:
file.write(str(mem) + '\n')
Here is the error:
[sessia1] Sleeping for 26s (required by "channels.GetMessages")
That is not an Error -
You cant get a all history with iter_history in one time
you should wait to iter_history generator finish !
I'm stuck with an error in telethon, when trying to get users data.
First, I get new messages from some groups, it's ok, but when I try to get user data (name, first_name etc) - sometimes it's ok, but mostly fails with error
ValueError: Could not find the input entity for "12345678".
Please read https://telethon.readthedocs.io/en/latest/extra/basic/entities.html
to find out more details.
I read that article a lot of times, tried to use also client.get_input_entity as it says, but it doesn't help
Here is my code:
import logging
from telethon import TelegramClient, events
logging.basicConfig(level=logging.WARNING)
logging.getLogger('asyncio').setLevel(logging.ERROR)
entity = 'session' # session
api_id = 123456
api_hash = 'hash'
phone = '1234567'
chats = ['group1', 'group2', 'group3']
client = TelegramClient(entity, api_id, api_hash)
#client.on(events.NewMessage(chats=chats))
async def normal_handler(event):
print(event.message.message)
print(event.date)
print(event.from_id)
print(event.message.to_id)
#user = await client.get_input_entity(event.from_id)
user = await client.get_entity(event.from_id)
client.start()
client.run_until_disconnected()
How can I fix that?
And one more question, how can I retrieve info about group?
I know it's id from event.message.to_id, but can't get how to get it's name.
The docs for the library looks not very friendly for beginners. =(
Thank you
Telegram does not allow to get user profile by integer id if current client had never "saw" it.
Telethon documentation (https://telethon.readthedocs.io/en/latest/extra/basic/entities.html) suggests following options to make contact "seen":
if you have open conversation: use client.get_dialogs()
if you are in same group: use client.get_participants('groupname')
if you are it was forward in group: use client.get_messages('groupname', 100)
Choose which one is applicable in your case. One of them will make contact "seen", and it will be possible to use client.get_entity(event.from_id)
i trying to add users by usernames to my channel. I am using python 3.6 telethon library and pythonanywhere server:
api_hash = 'b7**'
phone = '+7***'
client = TelegramClient('new_ses', api_id, api_hash)
client.connect()
client = TelegramClient('session_neworig', api_id, api_hash,)
client.connect()
from telethon.tl.functions.channels import InviteToChannelRequest
from telethon.tl.functions.contacts import ResolveUsernameRequest
from telethon.tl.types import InputPeerChannel ,InputPeerUser,InputUser
from telethon.tl.functions.channels import JoinChannelRequest
chann=client.get_entity('channelname') #its public channel
print(chann.id)
1161823752
print(chann.access_hash)
8062085565372622341
time.sleep(30)
chan=InputPeerChannel(chann.id, chann.access_hash)
user = client(ResolveUsernameRequest('Chai***'))
print(user.users[0].id)
193568760
print(user.users[0].access_hash)
-4514649540347033311
time.sleep(1*30)
user=InputUser(user.users[0].id,user.users[0].access_hash,)
client.invoke(InviteToChannelRequest(chan,[user]))
This dosent work and i get -telethon.errors.rpc_error_list.PeerFloodError: (PeerFloodError(...), 'Too many requests')
what am i doing wrong? how to avoid it ?
this one code is worked for me , but i am gone to flood after added let's say 20 users :
from telethon.helpers import get_input_peer
client.invoke(InviteToChannelRequest(
get_input_peer(client.get_entity(chan),
[get_input_peer(client.get_entity(user))]
))
Please help , how to add 200 users by username without any ban , maybe there is another way to do it by python ? another lib or by api ?
Found somethin on Telegram API documentation website
Each phone number is limited to only a certain amount of logins per day (e.g. 5, but this is subject to change) after which the API will return a FLOOD error until the next day. This might not be enough for testing the implementation of User Authorization flows in client applications.
Link to source
from telethon.sync import TelegramClient
from telethon.tl.functions.channels import InviteToChannelRequest
from telethon.tl.types import InputPeerChannel ,InputUser
from telethon.tl.functions.contacts import ResolveUsernameRequest
api_id = ******
api_hash = '******'
phone = '+2519******'
client = TelegramClient(phone, api_id, api_hash);
client.connect()
chann=client.get_entity('channelname')
channel_id = chann.id;
channel_access_hash = chann.access_hash
chanal=InputPeerChannel(channel_id, channel_access_hash)
user = client(ResolveUsernameRequest('mrmi6'))
user=InputUser(user.users[0].id,user.users[0].access_hash,)
client(InviteToChannelRequest(chanal,[user]))
print('action completted')