Navigation X
ALERT
Click here to register with a few steps and explore all our cool stuff we have to offer!



 1720

Need some help with Python

by Timo - 31 May, 2021 - 09:15 PM
This post is by a banned member (Timo) - Unhide
Timo  
Supreme
249
Posts
31
Threads
5 Years of service
#1
Not really experienced with python at all.
Trying to run this script:
 
Code:
 
######
#
# Telelooper - Simple Telegram to Discord relay service, but this one loops once a second
#
######

from discord_hooks import Webhook
from telethon import TelegramClient
from telethon.tl.functions.messages import GetDialogsRequest, GetHistoryRequest
from telethon.tl.functions.channels import GetFullChannelRequest
from telethon.tl.functions.updates import GetChannelDifferenceRequest
from telethon.tl.types import UpdateShortMessage, UpdateNewChannelMessage, PeerUser, PeerChat, PeerChannel, InputPeerEmpty, Channel, ChannelMessagesFilter, ChannelMessagesFilterEmpty
from time import sleep
import json
import os
import requests
import logging
import pprint
pp = pprint.PrettyPrinter(indent=4)
#logging.basicConfig(level=logging.DEBUG)
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s', datefmt='%m-%d %H:%M')
logger = logging.getLogger('telebagger')

with open('config.json') as config_file:
    config = json.load(config_file)


try:
    url = config['discord']['url']
    api_id = config['telegram']['api_id']
    api_hash = config['telegram']['api_hash']
    phone = config['telegram']['phone']
    channel_id = config['telegram']['channel_id']
    everyone = config['telegram']['everyone']
    loglevel = config['telegram']['loglevel']
except:
    logger.error('Error processing config file')

logger.setLevel(loglevel)

print('Connecting to Telegram...')

tclient = TelegramClient('session_name', api_id, api_hash)
tclient.connect()
if not tclient.is_user_authorized():
    tclient.send_code_request(phone)
    myself = tclient.sign_in(phone, input('Enter code: '))

lastmessage = 0
last_date = None
chunk_size = 20
chan_type = 'channel'
result = tclient(GetDialogsRequest(
                 offset_date=last_date,
                 offset_id=0,
                 offset_peer=InputPeerEmpty(),
                 limit=chunk_size
             ))
pp.pprint(result)
print("\nAvailable Channels:")
for p in result.chats:
    if type(p) is Channel:
        print(str(p.id)+": "+p.title)
        if p.id == channel_id:
            channel_name = p.title
            print(p.stringify())
            chan_type = 'channel'
for u in result.users:
    print(str(u.id)+": "+u.first_name)
    if u.id == channel_id:
        channel_name = u.first_name
        print(u.stringify())
        chan_type = 'user'
# for d in result.dialogs:
#     print(d.stringify())

if chan_type == 'channel':
    channelEnt = tclient.get_input_entity(PeerChannel(channel_id))
else:
    channelEnt = tclient.get_input_entity(PeerUser(channel_id))

try:
    logger.info("\nListening for messages from channel '{}' with ID '{}'".format(channel_name,channel_id))
except:
    logger.error("Whoops! Couldn't find channel ID '{}'".format(channel_id))

history = tclient(GetHistoryRequest(peer=channelEnt,
                                            offset_date=last_date,
                                            offset_id=0,
                                            add_offset=0,
                                            limit=10,
                                            max_id=0,
                                            min_id=0,
                                            hash=0
                                        ))
history.messages.reverse()
logger.info("\nLast 10 Messages:\n")
for m in history.messages:
    datetime = m.date.strftime('%Y-%m-%d %H:%M:%S')
    try:
        logger.info(datetime+" "+str(m.id)+": "+m.message)
    except:
        continue
    if m.id > lastmessage:
        lastmessage = m.id
    try:
        logger.info("Relaying Message {}".format(m.id))
        media = m.media
        if media is not None:
            logger.info("Would download image")
            logger.debug(media)
            # download_res = tclient.download_media(
            #     media, './downloads/')
            # logger.info("Download done: {}".format(download_res))
            # files = {'file': (open(download_res, 'rb'))}
            # response = requests.post(url, files=files)
            # logger.debug(response.text)
            # os.remove(download_res)
            # logger.debug("File deleted")
        if not m.message == '':
            if everyone:
                msgText = "@noteveryone {}".format(m.message)
            else:
                msgText = "{}".format(m.message)
            #msg = Webhook(url,msg=msgText)
            #msg.post()
    except:
        logger.info('Ignoring empty message {} action: {}'.format(m.id, m.action))
    try:
        logger.info(datetime+" "+str(m.id)+": "+m.message)
    except:
        logger.debug(m)

while True:
    try:
        messages = tclient(GetHistoryRequest(peer=channelEnt,
                                            offset_date=last_date,
                                            offset_id=0,
                                            add_offset=0,
                                            limit=50,
                                            max_id=0,
                                            min_id=lastmessage,
                                            hash=0
                                        ))
        if len(messages.messages) > 0:
            logger.debug('New Messages: ')
            logger.debug(messages)
            for m in messages.messages:
                datetime = m.date.strftime('%Y-%m-%d %H:%M:%S')
                if m.id > lastmessage:
                    lastmessage = m.id
                try:
                    logger.info("Relaying Message {}".format(m.id))
                    media = m.media
                    if media is not None:
                        logger.info("Will download image")
                        logger.debug(media)
                        download_res = tclient.download_media(
                            media, './downloads/')
                        logger.info("Download done: {}".format(download_res))
                        files = {'file': (open(download_res, 'rb'))}
                        response = requests.post(url, files=files)
                        logger.debug(response.text)
                        os.remove(download_res)
                        logger.debug("File deleted")
                    if not m.message == '':
                        if everyone:
                            msgText = "@everyone {}".format(m.message)
                        else:
                            msgText = "{}".format(m.message)
                        msg = Webhook(url,msg=msgText)
                        msg.post()
                except:
                    logger.info('Ignoring empty message {} action: {}'.format(m.id, m.action))
                try:
                    logger.info(datetime+" "+str(m.id)+": "+m.message)
                except:
                    logger.debug(m)
        sleep(2)
        continue
    except KeyboardInterrupt:
        break

tclient.disconnect()

I get the following error:
Code:
 
C:\Users\Gebruiker\Documents\Telegram predictor\telebagger-master\telebagger-master\telelooper.py:44: RuntimeWarning: coroutine 'TelegramBaseClient.connect' was never awaited
  tclient.connect()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
C:\Users\Gebruiker\Documents\Telegram predictor\telebagger-master\telebagger-master\telelooper.py:45: RuntimeWarning: coroutine 'UserMethods.is_user_authorized' was never awaited
  if not tclient.is_user_authorized():
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Traceback (most recent call last):
  File "C:\Users\Gebruiker\Documents\Telegram predictor\telebagger-master\telebagger-master\telelooper.py", line 53, in <module>
    result = tclient(GetDialogsRequest(
TypeError: __init__() missing 1 required positional argument: 'hash'

Anyone got a clue how to fix this?
This post is by a banned member (slashslash) - Unhide
28
Posts
3
Threads
4 Years of service
#2
the connect method of the class TelegramClient is expecting one input, I suggest you read more about the module and see what this method is expecting: https://docs.telethon.dev/en/latest/modules/client.html
This post is by a banned member (Timo) - Unhide
Timo  
Supreme
249
Posts
31
Threads
5 Years of service
#3
(31 May, 2021 - 09:39 PM)slashslash Wrote: Show More
the connect method of the class TelegramClient is expecting one input, I suggest you read more about the module and see what this method is expecting: https://docs.telethon.dev/en/latest/modules/client.html

Tbh i have no clue about Python.
My coder is gone for a bit so i'm just trying to get this up and running but no clue what the more complicated stuff means.
Isn't there a quick fix? If not ill just wait i guess.

Really appreciate your help tho man.
This post is by a banned member (slashslash) - Unhide
28
Posts
3
Threads
4 Years of service
#4
(This post was last modified: 31 May, 2021 - 10:10 PM by slashslash.)
well, let me take a closer look and get back to you

I don't have telegram API creds, so unless you want to share yours with me (which I don't suggest), I can only guess. At first glance it looks like you need to add this line "tclient.start()" to initiate the class before you start the tclient.connect(), not sure if tclient.connect() will be needed at all but you can try adding tclient.start() and see what happens
This post is by a banned member (Timo) - Unhide
Timo  
Supreme
249
Posts
31
Threads
5 Years of service
#5
(This post was last modified: 01 June, 2021 - 05:42 PM by Timo.)
(31 May, 2021 - 09:55 PM)slashslash Wrote: Show More
well, let me take a closer look and get back to you

I don't have telegram API creds, so unless you want to share yours with me (which I don't suggest), I can only guess. At first glance it looks like you need to add this line "tclient.start()" to initiate the class before you start the tclient.connect(), not sure if tclient.connect() will be needed at all but you can try adding tclient.start() and see what happens

I got further this time with what you said!
But after a bit it showed the same error again (Number, IP, and code are replaced by XXXXX):
Code:
 
C:\Users\Gebruiker\AppData\Local\Microsoft\WindowsApps\python3.9.exe "C:/Users/Gebruiker/Documents/Telegram predictor/telebagger-master/telebagger-master/telelooper.py"
Connecting to Telegram...
06-01 17:37 telethon.network.mtprotosender INFO     Connecting to xxx.xxx.167.51:443/TcpFull...
06-01 17:37 telethon.network.mtprotosender INFO     Connection to xxx.xxx.167.51:443/TcpFull complete!
Please enter your phone (or bot token): xxxxxxxx
06-01 17:37 telethon.client.users INFO     Phone migrated to 4
06-01 17:37 telethon.client.telegrambaseclient INFO     Reconnecting to new data center 4
06-01 17:37 telethon.network.mtprotosender INFO     Disconnecting from xxx.xxx.167.51:443/TcpFull...
06-01 17:37 telethon.network.mtprotosender INFO     Disconnection from xxx.xxx.167.51:443/TcpFull complete!
06-01 17:37 telethon.network.mtprotosender INFO     Connecting to xxx.xxx.167.91:443/TcpFull...
06-01 17:37 telethon.network.mtprotosender INFO     Connection to xxx.xxx.167.91:443/TcpFull complete!
Please enter the code you received: XXXXX
Signed in successfully as Timo
C:\Users\Gebruiker\Documents\Telegram predictor\telebagger-master\telebagger-master\telelooper.py:45: RuntimeWarning: coroutine 'TelegramBaseClient.connect' was never awaited
  tclient.connect()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
C:\Users\Gebruiker\Documents\Telegram predictor\telebagger-master\telebagger-master\telelooper.py:46: RuntimeWarning: coroutine 'UserMethods.is_user_authorized' was never awaited
  if not tclient.is_user_authorized():
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Traceback (most recent call last):
  File "C:\Users\Gebruiker\Documents\Telegram predictor\telebagger-master\telebagger-master\telelooper.py", line 54, in <module>
    result = tclient(GetDialogsRequest(
TypeError: __init__() missing 1 required positional argument: 'hash'

Process finished with exit code 1

Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
or
Sign in
Already have an account? Sign in here.


Forum Jump:


Users browsing this thread: 1 Guest(s)