telethon forwarding messages to group - python

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

Related

I'm using Python and Telethon as a Telegram client to get new messages, but need to identify a reply and which message it replying to

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

How to use NewMessage event of telethon on google colab

I have this code and I want to run it on google colab. It works great on my PC but on colab I always get errors like these:
SyntaxError: 'async with' outside async function
or
RuntimeError: You must use "async with" if the event loop is running (i.e. you are inside an "async def")
sometimes it does not wait for getting new messages and finish after one running.
import json
import time
import telethon as tlt
import asyncio
from telethon import events,TelegramClient
chat_name = "sample"
telegram_session="sample_1"
api_id = "0000000"
api_hash = ""
client = TelegramClient(None , api_id, api_hash)
#client.on(events.NewMessage(chats=chat_name))
async def handler(event):
get_message = event.message.to_dict()
get_message['date'] = get_message['date'].strftime("%Y-%m-%d %H:%M:%S")
message_json = json.dumps(get_message)
print(message_json)
async with client:
client.run_until_disconnected()
You need to put async with inside of async def:
...
async def main():
async with client:
await client.run_until_disconnected()
client.loop.run_until_complete(main())

Get data from stats channel request api telegram

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())```

Telethon event handler stuck looping

I've been trying to send my client's incoming messages via my bot back to the client. The event handler get stuck in a loop doing so. I'm still new to asynchronous programming and telethon, any feedback or specific reference is highly appreciated. :-)
from telethon import TelegramClient, client, events
api_id = xxx
api_hash = 'xxx'
telegram_bot_token = 'xxx'
telegram_chat_id = 'xxx'
bot = TelegramClient('xxx', api_id, api_hash).start(bot_token='xxx')
client = TelegramClient('xxx', api_id, api_hash)
#client.on(events.NewMessage)
async def messaged_by_bot(event):
await bot.send_message('xxx', event.message.text)
client.start()
client.run_until_disconnected()

Telegram's websocket

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()

Categories