I want to get statistics data channel from telegram api. I wrote and run this code but get an error:
telethon.errors.rpcerrorlist.ChatAdminRequiredError: Chat admin privileges are required to do that in the specified chat (for example, to send a message in a channel which is not yours), or invalid permission
s used for the channel or group (caused by GetBroadcastStatsRequest)
Please help me check and fix it. Thank a lot !
p/s: This is my channel
import configparser
from telethon.tl.types import ChannelParticipantsSearch
from telethon.tl.functions.channels import GetFullChannelRequest
from telethon import functions, types
from telethon.tl.functions.stats import GetBroadcastStatsRequest
from telethon.tl.types import PeerUser, PeerChat, PeerChannel
from telethon.tl.types import InputChannel
config = configparser.ConfigParser()
config.read("config.ini")
api_id = config['Telegram']['api_id']
api_hash = config['Telegram']['api_hash']
api_hash = str(api_hash)
phone = config['Telegram']['phone']
username = config['Telegram']['username']
channel = 'https://t.me/testapi2607'
id_channel = 1523534046
access_hash = 7456721436474437
client = TelegramClient(username, api_id, api_hash)
async def main():
await client.start()
print("Client Created")
# Ensure you're authorized
if await client.is_user_authorized() == False:
await client.send_code_request(phone)
try:
await client.sign_in(phone, input('Enter the code: '))
except SessionPasswordNeededError:
await client.sign_in(password=input('Password: '))
me = await client.get_me()
await client.get_entity(PeerChannel(1523534046))
my_channel = InputChannel(id_channel, access_hash)
result = await client(functions.stats.GetBroadcastStatsRequest(channel = my_channel, dark=True))
print(str(result))
with client:
client.loop.run_until_complete(main())```
Related
Objective: Use A's API ID and API hash to sign in to B's phone
`
from telethon import TelegramClient, events, sync
import asyncio
api_id = [A's API ID]
api_hash = [A's API hash]
client = TelegramClient('anon', api_id, api_hash)
#client.on(events.NewMessage)
async def my_event_handler(event):
await event.reply('hi')
client.start(phone='[B's phone]')
client.run_until_disconnected()
`
With the above code, result is as follows:
UserWarning: the session already had an authorized user so it did not login to the user account using the provided phone (it may not be using the user you expect)
A's account is still being used in the client.
I tried the client.sign_in method but not sure how to do it:
`
from telethon import TelegramClient, events, sync
import asyncio
api_id = [A's API ID]
api_hash = [A's API hash]
client = TelegramClient('anon', api_id, api_hash)
#client.on(events.NewMessage)
async def my_event_handler(event):
await event.reply('hi')
async def signin():
print('sign in')
await client.sign_in(phone='[B's phone]')
client.start()
asyncio.run(signin())
client.run_until_disconnected()
`
Result is stuck at "print('sign in') and nothing else happened.
I have a working Python script with Telethon and it logs in with my account, connects to the correct channel and gets new messages just fine. It also can identify if it is a new message vs a reply to a previous message. I just need to figure out which message the reply is replying to. Here is the code I have so far.
import requests
import configparser
import threading
from telethon import TelegramClient, events, sync
from telethon.errors import SessionPasswordNeededError
from telethon.tl.types import (
PeerChannel
)
from os import system
system("title " + "My Telegram Client")
# Reading Configs
config = configparser.ConfigParser()
config.read("config.ini")
# Setting configuration values
api_id = config['Telegram']['api_id']
api_hash = config['Telegram']['api_hash']
api_hash = str(api_hash)
phone = config['Telegram']['phone']
username = config['Telegram']['username']
subjectFilter = ['']
levelFilter = ['']
client = TelegramClient(username, api_id, api_hash)
async def main(phone):
await client.start()
print("TELEGRAM CLIENT CREATED")
# Ensure you're authorized
if await client.is_user_authorized() == False:
await client.send_code_request(phone)
try:
await client.sign_in(phone, input('Enter the code: '))
except SessionPasswordNeededError:
await client.sign_in(password=input('Password: '))
me = await client.get_me()
user_input_channel=PeerChannel(int(-1172633073)) #BL TECH PRO
print("Connected to BL Tech Pro Telegram Channel")
#client.on(events.NewMessage(chats=user_input_channel))
async def newMessageListener(event):
newMessage = event.message.message
#CHECK IF MESSAGE IS A REPLY
if event.message.is_reply:
print("reply")
else:
print("not reply")
#PRINT MESSAGE TO SCREEN
print(newMessage)
client.start()
client.run_until_disconnected()
After a lot of testing, I figured it out.
This prints out the original message with all the message properties:
if event.message.is_reply:
orgMessage = await event.get_reply_message()
print("reply")
print(orgMessage)
else:
print("not reply")
I'm creating a script to forward messages it worked perfectly, but I created a graphical interface and put the id group data in tkinter entries, and then the code stopped working I also put the ids in inputs and it doesn't work,
the code runs but does not forward the msg would anyone know how to solve it
from telethon import TelegramClient, events
import asyncio
with open('Id1.txt', 'r')as f:
Id_Group1 = f.read()
with open('Id2.txt', 'r')as j:
Id_Group2 = j.read()
print (Id_Group1, Id_Group2)
api_id = '#######'
api_hash = '#######################'
client = TelegramClient('none', api_id, api_hash)
#client.on(events.NewMessage)
async def handler(event):
chat = await event.get_chat()
chat_id = event.chat_id
print('{} {}'.format(chat_id, chat))
if chat_id == Id_Group1:
await client.send_message(Id_Group2, event.raw_text)
client.start()
client.run_until_disconnected()
This is not working because your code in if condition will never execute.
The problem is
chat_id is and Integer and
Id_Group1 is a String.
according to python and almost all other programming language.
"-1001659707082" is not equal to -1001659707082
Here is the modified codes..
import asyncio
from telethon import TelegramClient
from telethon.sync import events
Id_Group1 = "-1001659707082"#You can add username and add entity thing instead
Id_Group2 = "thisistest_2"
api_id = 123
api_hash = "12gh3"
print (Id_Group1, Id_Group2)
client = TelegramClient('none', api_id, api_hash)
#client.on(events.NewMessage)
async def handler(event):
chat = await event.get_chat()
chat_id = event.chat_id
if str(chat_id) == Id_Group1:
print('{} {}'.format(chat_id, chat))
await client.send_message(Id_Group2, event.text)
client.start()
client.run_until_disconnected()
Also watch the Id_Group1 and Id_Group2
I want to connect to the telegram's WebSocket or other protocol, to receive every message. I was inspecting the network tab in dev tools, but I could not find any WebSocket protocol, however, when I entered console, I can see [SW] on message {type: "ping", localNotifications: true, lang: {…}, settings: {…}} Which convince me, that it is sent to maintain connection with the WebSocket. I tried a telethon library for python, but it allows me only to show all messages in the chat.
from telethon import TelegramClient
import asyncio
client = TelegramClient(name, api_id, api_hash)
client.start()
for i in client.iter_dialogs():
if i.name == 'test':
chj = i
async def main():
channel = await client.get_entity(chj)
messages = await client.get_messages(channel, limit= None) #pass your own args
#then if you want to get all the messages text
for x in messages:
print(x) #return message.text
"""for i in client.iter_dialogs():
print(i)"""
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
I want to be getting messages like in WebSocket whenever on the desired chat someone's types something
I have found an answer. This can be achieved using events from telethon library
from telethon import TelegramClient, events
name = 'test'
api_id = 1234
api_hash = 'hash'
client = TelegramClient(name, api_id, api_hash)
#client.on(events.NewMessage())
async def newMessageListener(event):
newMessage = event.message.message
print(newMessage)
with client:
client.run_until_disconnected()
i use this script for connect and create sessions in telethon
from telethon import TelegramClient
from telethon.tl.functions.messages import GetHistoryRequest
from telethon.utils import get_input_peer
api_id = 7****
api_hash = 'ef584d*****************'
client = TelegramClient('+15159947451', api_id, api_hash)
client.connect()
if not client.is_user_authorized():
client.send_code_request('+15159947451')
client.sign_in('+15159947451', cod)
with this cod i can login good in this number telegram and create file:+15159947451.session.
now i close and disconnect, how i can again login this number with this file +15159947451.session.
i use this code but this code have error:
from telethon import TelegramClient
from telethon.tl.functions.messages import GetHistoryRequest
from telethon.utils import get_input_peer
api_id = 7****
api_hash = 'ef584d180eee*******************'
number='+15152934803'
client = TelegramClient('00', api_id, api_hash)
client.session.try_load_or_create_new(session_user_id='+15159947451')
client.connect()
but i have this error
raise error
telethon.errors.RPCError: (RPCError(...), 'AUTH_KEY_UNREGISTERED (401): The key is not registered in the system.')
The problem is this line:
client = TelegramClient('+15xxxxxxxxx', api_id, api_hash)
You don't have to pass your phone number as a first parameter. You have to pass the name of the session, for instance, 'myname'.
You get this:
telethon.errors.RPCError: (RPCError(...), 'AUTH_KEY_UNREGISTERED (401): The key is not registered in the system.')
Because you've changed the name of the session (and now called it '00'), and you haven't logged it on that one. So in order to solve your problem simply:
client = TelegramClient('some_name', api_id, api_hash)
client.connect()
if not client.is_user_authorized():
client.send_code_request('+15xxxxxxxxx')
client.sign_in('+15xxxxxxxxx', cod)
And then remove the .send_code_request(...) line:
client = TelegramClient('some_name', api_id, api_hash)
client.connect()
Notice that if you change 'some_name' for some .session that doesn't exist yet, you will have to create it again. Also, you can rename the .session file to any name you want, and use its name as a parameter (since it already exists).
from telethon import TelegramClient
# These example values won't work. You must get your own api_id and
# api_hash from https://my.telegram.org, under API Development.
api_id = ****** # Your api_id
api_hash = '********************************' # Your api_hash
phone_number = '+989122594574' # Your phone number
client = TelegramClient(phone_number, api_id, api_hash)
client.connect()
if not client.is_user_authorized():
client.send_code_request(phone_number)
client.sign_in(phone_number, input('Enter the code: '))
client.send_message('amir2b', 'Hello! Amir Bashiri')