def __init__(self, bot):
        self.bot = bot
        self.no_threads = True
        self.phone = None
        self.bot_token = None

        if self.bot.config['bindings_token'].startswith('+'):
            self.phone = self.bot.config['bindings_token']
        else:
            self.bot_token = self.bot.config['bindings_token']

        self.client = Telegram(
            api_id=self.bot.config['api_keys']['telegram_app_id'],
            api_hash=self.bot.config['api_keys']['telegram_api_hash'],
            phone=self.phone,
            bot_token=self.bot_token,
            database_encryption_key=self.bot.config['api_keys']
            ['database_encryption_key'],
            library_path='/usr/local/lib/libtdjson.so',
            files_directory='{}/.tdlib_files/{}/'.format(
                os.getcwd(), self.bot.name),
            device_model='polaris',
            application_version='1.0',
            tdlib_verbosity=1,
        )
        self.client.login()
async def main():
    session_files = [
        session_file_name
        for session_file_name in os.listdir(TELETHON_SESSIONS_FOLDER_NAME)
        if os.path.splitext(session_file_name)[1] == ".session"
    ]
    context = Context(amount_of_accounts_to_process=len(session_files))
    for session_file_name in session_files:
        client = telethon.TelegramClient(
            os.path.join(TELETHON_SESSIONS_FOLDER_NAME, session_file_name),
            api_id=CONFIG["api_id"], api_hash=CONFIG["api_hash"]
        )
        await client.connect()
        try:
            phone = (await client.get_me()).phone
        except AttributeError:  # 'NoneType' object has no attribute 'phone'
            print(f"`{session_file_name}` isn't logged in! Skipping it.")
            continue
        tdlib_session = Telegram(
            api_hash=CONFIG["api_hash"],
            api_id=CONFIG["api_id"],
            database_encryption_key=CONFIG["tdlib_database_encryption_key"],
            files_directory=os.path.join(TDLIB_SESSIONS_FOLDER_NAME, phone),
            phone=phone, tdlib_verbosity=0
        )
        tdlib_session.login(blocking=False)
        client.add_event_handler(
            functools.partial(
                check_incoming_tg_message, context, client, tdlib_session
            ), event=NewMessage()
        )
        # noinspection PyTypeChecker,PyUnresolvedReferences
        await client.start()
 def test_phone_bot_token_init(self):
     with pytest.raises(ValueError) as excinfo:
         Telegram(
             api_id=API_ID,
             api_hash=API_HASH,
             library_path=LIBRARY_PATH,
             database_encryption_key=DATABASE_ENCRYPTION_KEY,
         )
         assert 'You must provide bot_token or phone' in str(excinfo.value)
def telegram(mocker):
    with mocker.mock_module.patch('telegram.client.TDJson'):
        with mocker.mock_module.patch('telegram.client.threading'):
            tg = Telegram(
                api_id=API_ID,
                api_hash=API_HASH,
                phone=PHONE,
                library_path=LIBRARY_PATH,
                database_encryption_key=DATABASE_ENCRYPTION_KEY,
            )
    return tg
示例#5
0
def init_telegram():
    t = Telegram(api_id=app_config.app_id,
                 api_hash=app_config.api_hash,
                 phone=app_config.phone,
                 database_encryption_key=app_config.database_encryption_key,
                 tdlib_verbosity=app_config.tdlib_verbosity)

    t.login()
    chats = t.get_chats()
    chats.wait()

    return t
def _get_telegram_instance(**kwargs):
    kwargs.setdefault('api_id', API_ID)
    kwargs.setdefault('api_hash', API_HASH)
    kwargs.setdefault('phone', PHONE)
    kwargs.setdefault('library_path', LIBRARY_PATH)
    kwargs.setdefault('database_encryption_key', DATABASE_ENCRYPTION_KEY)

    with patch('telegram.client.TDJson'):
        with patch('telegram.client.threading'):
            tg = Telegram(**kwargs)

    return tg
示例#7
0
def login():
    tg = Telegram(
        api_id=api_id,
        api_hash=api_hash,
        phone=phone,
        database_encryption_key=database_encryption_key,
        proxy_server=proxy_server,
        proxy_port=proxy_port,
        proxy_type=proxy_type,
    )
    tg.login()

    return tg
示例#8
0
def bot_get_me(api_id, api_hash, token):
    tg = Telegram(
        api_id=api_id,
        api_hash=api_hash,
        bot_token=token,
        database_encryption_key='changeme1234',
    )
    # you must call login method before others
    tg.login()

    result = tg.get_me()
    result.wait()
    print(result.update)
    tg.stop()
示例#9
0
    def __init__(self, phone: str, files_directory: str = None) -> None:
        assert phone.startswith(
            '+'), f'the phone number must have a "+" prefix, had {phone}'
        self.logger.debug(f'Login as {phone}')

        self.tg = Telegram(
            api_id='94575',
            api_hash='a3406de8d171bb422bb6ddf3bbd800e2',
            phone=phone,
            files_directory=files_directory,
            database_encryption_key='dfaafaad2972d7636bf277ab',
        )

        self.results = {}
        self.tg.add_update_handler('updateFile', self._update_file_handler)
        self.tg.add_update_handler('updateMessageSendSucceeded',
                                   self._update_message_send_succeeded_handler)
        self.tg.login()
示例#10
0
def init():
    utils.setup_logging()

    parser = argparse.ArgumentParser()
    utils.add_api_args(parser)
    utils.add_proxy_args(parser)
    args = parser.parse_args()

    tg = Telegram(
        api_id=args.api_id,
        api_hash=args.api_hash,
        phone=args.phone,
        database_encryption_key=args.db_key,
        proxy_server=args.proxy_server,
        proxy_port=args.proxy_port,
        proxy_type=utils.parse_proxy_type(args)
    )
    tg.login()

    return tg
示例#11
0
def login():
    """
        This function creates and authenticates Telegram client
        and calls the call_back with Telegram client, phone no
        and chat id as arguments.
    """

    (ph_no, chat_id, bup_folders) = load_data()

    tg_client = Telegram(api_id=API_ID,
                         api_hash=API_HASH,
                         files_directory=FILES_DIR,
                         database_encryption_key=DATABASE_ENCRYPTION_KEY,
                         tdlib_verbosity=0,
                         phone=ph_no)

    tg_client.call_method(
        "setTdlibParameters",
        {
            "use_file_database": True,
            "use_chat_info_database": True,
            "use_message_database": True,
            "application_version": VERSION
        },
    )

    if chat_id is None:
        print("A code has been sent to you via telegram.")

    try_login_with_code(tg_client)

    if chat_id is None:
        chat_id = get_chat_id(tg_client, ph_no, bup_folders)

        if confirm("Do you want to load previously backed-up file list?"):
            print("Getting file list, this might take some time...")
            tg_client.get_chats().wait()

    return tg_client, chat_id, bup_folders
示例#12
0
def main():
    utils.setup_logging()

    parser = argparse.ArgumentParser()
    utils.add_api_args(parser)
    utils.add_proxy_args(parser)
    args = parser.parse_args()

    tg = Telegram(api_id=args.api_id,
                  api_hash=args.api_hash,
                  phone=args.phone,
                  database_encryption_key='changeme1234',
                  proxy_server=args.proxy_server,
                  proxy_port=args.proxy_port,
                  proxy_type=utils.parse_proxy_type(args))
    # you must call login method before others
    tg.login()

    result = tg.get_me()
    result.wait()
    pprint(result.update)

    tg.stop()
示例#13
0
from telegram.client import Telegram, AuthorizationState
import logging

tg = Telegram(
    api_id='4880490',
    api_hash='f823748c0978b3067fd4c355d2ce58ed',
    phone='+375295179613',
    database_encryption_key='changeme1234',
)

state = tg.login(blocking=False)

if state == AuthorizationState.WAIT_CODE:
    # Telegram expects a pin code
    tg.send_code(input('Code: '))
    state = tg.login(blocking=False)  # continue the login process

if state == AuthorizationState.WAIT_REGISTRATION:
    logging.warning('registration')
    state = tg.register_user('test', 'name')
    logging.warning(state)

# docker build . -t testingfork:latest --platform linux/amd64
示例#14
0
文件: begin.py 项目: iCatOK/tutorbot
import telebot
from telegram.client import Telegram

tg = Telegram(
    api_id='223471',
    api_hash='35e5fd598146bd69a2225b5402ab706c',
    phone='+79273235411',
    database_encryption_key='changeme1234',
)
tg.login()


def new_message_handler(update):
    message_content = update['message']['content'].get('text', {})
    # we need this because of different message types: photos, files, etc.
    message_text = message_content.get('text', '').lower()

    if message_text == 'ping':
        chat_id = update['message']['chat_id']
        print(f'Ping has been received from {chat_id}')
        tg.send_message(
            chat_id=chat_id,
            text='pong',
        )


tg.add_message_handler(new_message_handler)
tg.idle()  # blocking waiting for CTRL+C


class Hero:
示例#15
0
    except ConnectionError as e:
        pretty_print(
            bmodes.DETECTOR,
            colored('ERROR', 'red') +
            colored('Redis connection error:', 'white'))
        print(e)
        exit()

#
#
#

# initialize telegram client
tg = Telegram(
    settings['telegram']['api-key'],
    settings['telegram']['api-hash'],
    database_encryption_key=settings['telegram']['database-encryption-key'],
    phone=settings['telegram']['phone'])

# login to telegram, you may have to input a 2fa-key
tg.login()

#
#
#


class User:
    def __init__(self,
                 id=None,
                 first_name=None,
示例#16
0
import os
from telegram.client import Telegram

API_ID = os.getenv("API_ID")
API_HASH = os.getenv("API_HASH")
BOT_TOKEN = os.getenv("BOT_TOKEN")
ENC_KEY = os.getenv("ENC_KEY")

tg = Telegram(
    api_id=API_ID,
    api_hash=API_HASH,
    bot_token=BOT_TOKEN,
    database_encryption_key=ENC_KEY,
)


def search_and_kick_out_spammers(update):
    msg_type = update["message"]["content"]["@type"]
    if msg_type == "messageChatAddMembers":
        chat_id = update["message"]["chat_id"]
        user_id = update["message"]["sender_user_id"]
        new_users = update["message"]["content"]["member_user_ids"]
        # Kick this user out of the group
        if user_id in new_users:
            params = {
                "chat_id": chat_id,
                "user_id": user_id,
                "status": {
                    "@type": "chatMemberStatusBanned"
                },
            }
示例#17
0
    parser.add_argument('api_hash', help='API hash')
    parser.add_argument('phone', help='Phone')
    parser.add_argument('chat_id', help='Chat ID')
    parser.add_argument('--limit',
                        help='Messages to retrieve',
                        type=int,
                        default=1000)
    parser.add_argument('--most-common',
                        help='Most common count',
                        type=int,
                        default=30)
    args = parser.parse_args()

    tg = Telegram(
        api_id=args.api_id,
        api_hash=args.api_hash,
        phone=args.phone,
        database_encryption_key='changeme1234',
    )
    # you must call login method before others
    tg.login()

    stats_data = retreive_messages(
        telegram=tg,
        chat_id=args.chat_id,
        receive_limit=args.limit,
    )

    print_stats(
        stats_data=stats_data,
        most_common_count=args.most_common,
    )
示例#18
0

# log to PushMe bot
def pushme(msg):
    requests.post("http://pushmebot.ru/send",
                  data={
                      'key': conf['pushmekey'],
                      'message': msg
                  })


pushme("Restarting worker...")

try:
    tg = Telegram(api_id=conf['auth']['id'],
                  api_hash=conf['auth']['hash'],
                  phone=conf['auth']['phone'],
                  database_encryption_key=conf['auth']['database_key'])

    tg.login()
except Exception:
    pushme('Login ERROR(')
else:
    pushme('Login success!')


def new_message_handler(update):
    message_content = update['message']['content'].get('text', {})
    message_text = message_content.get('text', '').lower()
    if message_text == 'ping':
        chat_id = update['message']['chat_id']
        pushme(f'Received new message from {chat_id}')
示例#19
0
from telegram.client import Telegram
import os
import pickle
import time

tg = Telegram(api_id='your_api_id',
              api_hash='your_hash',
              phone='your_phone',
              library_path='path_to_tdjson',
              database_encryption_key='any_key',
              files_directory='tmp')
tg.login()

result = tg.get_me()
result.wait()
chat_id = result.update[
    'id']  # seems like it also serves as saved messages chat id

orig_converted_msgs = pickle.load(open('orig_converted_msgs.pickle', 'rb'))
sleep_time = 1  # in seconds as a precaution against flood prevention delays


def check_request(request):
    request.wait()
    if request.error:
        print(request.error_info)
        time.sleep(2000)
    if 'sending_state' in request.update:
        if request.update['sending_state'] == 'messageSendingStatePending':
            print(msg_i, 'messageSendingStatePending')
            time.sleep(100)
'''
BEGIN:VCARD
VERSION:2.1
N:<LAST_NAME>;<FIRST_NAME>
FN:<FULL_NAME>
TEL;CELL:<PHONE_NO>
END:VCARD
'''

from telegram.client import Telegram

tg = Telegram(
    api_id='<API_ID>',
    api_hash='<API_HASH>',
    phone='<PHONE_NO>',  # you can pass 'bot_token' instead
    database_encryption_key='changekey123',
)
tg.login()


def getContacts(tg):
    contacts = tg._send_data({'@type': 'getContacts'})
    contacts.wait()
    contacts = contacts.update
    return contacts.get('user_ids', None)


def getUsers(tg, contacts):
    return (_getUser(tg, contact) for contact in contacts)

示例#21
0
import argparse

from telegram.client import Telegram
import utils

if __name__ == '__main__':
    utils.setup_logging()

    parser = argparse.ArgumentParser()
    utils.add_api_args(parser)
    utils.add_proxy_args(parser)
    args = parser.parse_args()

    tg = Telegram(
        api_id=args.api_id,
        api_hash=args.api_hash,
        phone=args.phone,
        database_encryption_key='changeme1234',
        proxy_server=args.proxy_server,
        proxy_port=args.proxy_port,
        proxy_type=utils.parse_proxy_type(args)
    )
    # you must call login method before others
    tg.login()

    result = tg.get_me()
    result.wait()
    print(result.update)
示例#22
0
    try:
        redis.ping()
    except ConnectionError as e:
        pretty_print(bmodes.DETECTOR, colored('ERROR', 'red') + colored('Redis connection error:', 'white'))
        print(e)
        exit()

#
#
#

# initialize telegram client
tg = Telegram(
    settings['telegram']['api-key'],
    settings['telegram']['api-hash'],
    database_encryption_key=settings['telegram']['database-encryption-key'],
    phone=settings['telegram']['phone'],
    default_workers_queue_size=10000
)

# login to telegram, you may have to input a 2fa-key
tg.login()

#
#
#

class User:
    def __init__(self, id = None, first_name = None, last_name = None, username = None, phone_number = None):
        self.id = id
        self.first_name = first_name
示例#23
0
from telegram.client import Telegram
import pprint
from postgres_connection import DB
import yaml

#load config:
with open('config.yml', 'r') as f:
    config = yaml.load(f)['default']
    print(config)

# global service objects:

tg = Telegram(api_id=config['app_id'],
              api_hash=config['api_hash'],
              phone=config['user_phone'],
              database_encryption_key='',
              use_message_database=False)

pp = pprint.PrettyPrinter(indent=2)
connection_string = "dbname={} user={} password={} host={} port={}".format(
    config['dbname'], config['dbuser'], config['dbpassword'], config['dbhost'],
    config['dbport'])
print(connection_string)
db = DB(connection_string=connection_string)

# end global service objects definitions


def fetch_and_store_chats(chat_ids):
    chats = []
    for id in chat_ids:
示例#24
0
    # Twitter setup
    with open('config/twitter.json') as f:
        twitterKeys = json.load(f)

    auth = tweepy.OAuthHandler(twitterKeys["consumer_key"],
                               twitterKeys["consumer_secret"])
    auth.set_access_token(twitterKeys["access_token_key"],
                          twitterKeys["access_token_secret"])

    twitterApi = tweepy.API(auth)

    # Telegram setup
    tg = Telegram(
        api_id=telegramKeys["api_id"],
        api_hash=telegramKeys["api_hash"],
        # phone='',  # you can pass 'bot_token' instead,
        bot_token=telegramKeys["bot_token"],  # nitowhalemanagerbot token
        database_encryption_key=telegramKeys["database_encryption_key"],
    )
    tg.login()

    # if this is the first run, library needs to preload all chats
    # otherwise the message will not be sent
    result = tg.get_chats()
    result.wait()


def globalErrorHandler(exceptionType, value, stackTrace):
    logging.exception("Globally handled exception")
    lock.set()
示例#25
0
    def _sendMessage(self, telegram_text):
        telegram_api_id = self.config.get("telegram_api_id", None)
        if telegram_api_id is None:
            raise self.server.error("telegram_api_id not configured!")
        telegram_api_hash = self.config.get("telegram_api_hash", None)
        if telegram_api_hash is None:
            raise self.server.error("telegram_api_hash not configured!")
        telegram_bot_token = self.config.get("telegram_bot_token", None)
        if telegram_bot_token is None:
            raise self.server.error("telegram_bot_token not configured!")
        telegram_database_encryption_key = self.config.get(
            "telegram_database_encryption_key", None)
        if telegram_database_encryption_key is None:
            raise self.server.error(
                "telegram_database_encryption_key not configured!")
        telegram_chat_id = self.config.get("telegram_chat_id", None)
        if telegram_chat_id is None:
            raise self.server.error("telegram_chat_id not configured!")
        telegram_code = self.config.get("telegram_code", None)
        if telegram_code is None:
            raise self.server.error("telegram_code not configured!")
        telegram_password = self.config.get("telegram_password", None)
        if telegram_password is None:
            raise self.server.error("telegram_password not configured!")

        try:
            logging.info(f"Login to telegram")
            tg = Telegram(
                api_id=telegram_api_id,
                api_hash=telegram_api_hash,
                phone=telegram_bot_token,  # you can pass 'bot_token' instead
                database_encryption_key=telegram_database_encryption_key)
            state = tg.login(blocking=False)

            if state == AuthorizationState.WAIT_CODE:
                # Telegram expects a pin code
                tg.send_code(telegram_code)
                state = tg.login(blocking=False)  # continue the login process

            if state == AuthorizationState.WAIT_PASSWORD:
                tg.send_password(telegram_password)
                state = tg.login(blocking=False)  # continue the login process

            if state != AuthorizationState.READY:
                raise self.server.error(
                    f"Error at the telegram login. Authorization state: {tg.authorization_state}"
                )

            logging.info(f"Loading chats")
            # if this is the first run, library needs to preload all chats
            # otherwise the message will not be sent
            result = tg.get_chats()
            result.wait()

            logging.info(f"Sending message: to chat {telegram_chat_id}")
            result = tg.send_message(
                chat_id=telegram_chat_id,
                text=telegram_text,
            )

            # `tdlib` is asynchronous, so `python-telegram` always returns you an `AsyncResult` object.
            # You can receive a result with the `wait` method of this object.
            result.wait()
            logging.info(result.update)

            tg.stop()  # you must call `stop` at the end of the script
        except Exception as e:
            logging.error("Error: unable to send message to channel", e)
示例#26
0

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('api_id',
                        help='API id')  # https://my.telegram.org/apps
    parser.add_argument('api_hash', help='API hash')
    parser.add_argument('phone', help='Phone nr originating call')
    parser.add_argument('user_id', help='User ID to call')
    parser.add_argument('dbkey', help='Database encryption key')
    args = parser.parse_args()

    tg = Telegram(api_id=args.api_id,
                  api_hash=args.api_hash,
                  phone=args.phone,
                  td_verbosity=5,
                  files_directory=os.path.expanduser("~/.telegram/" +
                                                     args.phone),
                  database_encryption_key=args.dbkey)
    tg.login()

    # if this is the first run, library needs to preload all chats
    # otherwise the message will not be sent
    r = tg.get_chats()
    r.wait()

    r = tg.call_method(
        'createCall', {
            'user_id': args.user_id,
            'protocol': {
                'udp_p2p': True,
示例#27
0
from telegram.client import Telegram

tg = Telegram(
    api_id='api_id',
    api_hash='api_hash',
    phone='+31611111111',
    database_encryption_key='changeme1234',
)
tg.login()


def new_message_handler(update):
    # we want to process only text messages
    message_content = update['message']['content'].get('text', {})
    message_text = message_content.get('text', '').lower()

    if message_text == 'ping':
        chat_id = update['message']['chat_id']
        print(f'Ping has been received from {chat_id}')
        tg.send_message(
            chat_id=chat_id,
            text='pong',
        )


tg.add_message_handler(new_message_handler)
tg.idle()
示例#28
0
            'date': data['date']
        }

        url_id = data['url_id']
        pr_dir = os.path.join(PROCESSED_DIR, url_id)
        create_dir(pr_dir)

        util.save_json_file(os.path.join(pr_dir, 'data.json'), product)

        print(product)


if __name__ == '__main__':
    tg = Telegram(
        api_id=API_ID,
        api_hash=API_HASH,
        phone=PHONE,
        database_encryption_key=DATABASE_ENCRYPTION_KEY,
    )

    tg.login()

    DOWNLOAD = False

    result = tg.call_method('searchPublicChat',
                            params={'username': '******'})
    result.wait()

    if 'id' in result.update:
        chat_id = result.update['id']

    if DOWNLOAD:
示例#29
0
from telegram.client import Telegram
from json import dumps
from secret import *

client = Telegram(
    api_id=API_ID,
    api_hash=API_HASH,
    phone=PHONE_NUMBER,
    database_encryption_key=DBENC,
)

client.login()


def new_message_handler(update):
    print(dumps(update['message']['chat_id'], indent=4))
    if str(update['message']['chat_id']) == CHAT_ID_SENDER:
        print(dumps(update, indent=4))
        message_content = update['message']['content'].get('text', {})
        message_entities = message_content.get('entities', '')
        message_text = message_content.get('text', {})
        print('\n\n\n', 'Encaminhando mensagem', '\n\n\n')
        client.send_message(
            chat_id=CHAT_ID_RECEIVER,
            text=message_text,
        )


client.add_message_handler(new_message_handler)
client.idle()
示例#30
0
######################

src_chat = getenv("SOURCE") or None
dst_chat = getenv("DESTINATION") or None

###########################
# Telegram Configurations #
###########################

tg = Telegram(
    api_id=getenv("API_ID"),
    api_hash=getenv("API_HASH"),
    phone=getenv("PHONE"),
    database_encryption_key=getenv("DB_PASSWORD"),
    files_directory=getenv("FILES_DIRECTORY"),
    proxy_server=getenv("PROXY_SERVER"),
    proxy_port=getenv("PROXY_PORT"),
    proxy_type={
        # 'proxyTypeSocks5', 'proxyTypeMtproto', 'proxyTypeHttp'
        '@type': getenv("PROXY_TYPE"),
    },
)

###############
# App methods #
###############


def copy_message(from_chat_id: int,
                 message_id: int,
                 send_copy: bool = True) -> None: