def sendMessage(receiver, message):

    # creating a telegram session and assigning
    # it to a variable client
    client = TelegramClient("session", API_ID, API_HASH)

    # connecting and building the session
    client.connect()

    # in case of script ran first time it will
    # ask either to input token or otp sent to
    # number or your telegram id
    if not client.is_user_authorized():
        client.send_code_request(PHONE)

        # signing in the client
        client.sign_in(PHONE, input("Enter the code: "))

    try:

        # sending message using telegram client
        client.send_message(receiver, message)

    except Exception as e:
        print(e)

    # disconnecting the telegram session
    client.disconnect()
示例#2
0
def send_message(message):
    # Create a telegram session and assign it to a variable client
    client = TelegramClient('session', api_id, api_hash)
    client.connect()

    # In case of script ran first time it will ask either to input token or otp sent to number or sent or your telegram id
    if not client.is_user_authorized():
        client.send_code_request(phone_number)
        # Signing in the client
        client.sign_in(phone_number, input('Enter the code: '))

    try:
        for receiver in receivers:
            # Set receiver user_id and access_hash
            # To get userid and access hash: client.get_input_entity('@username')
            receiverUser = InputPeerUser(receiver['user_id'],
                                         receiver['access_hash'])

            # Send message using telegram client
            client.send_message(receiverUser, message)
    except Exception as e:
        # there may be many error coming in while like peer error, wwrong access_hash, flood_error, etc
        print(e)

    # Disconnecting the telegram session
    client.disconnect()
示例#3
0
def send_message_to_channel() -> None:
    with open('setting.json', 'r', encoding='utf') as out:
        setting = json.load(out)

        client = TelegramClient('session', setting['account']['api_id'],
                                setting['account']['api_hash'])

    client.start()

    dialog = setting['channel']['name']
    messages = client.get_messages(dialog, limit=None)

    messages = [message for message in messages \
                if message.date.strftime('%m-%d-%Y') == datetime.now().strftime('%m-%d-%Y')]

    fcoins_sum = []
    rub_sum = []

    for message in messages:
        try:
            fcoins_sum.append(float(search_sum(message.message)))
        except:
            pass

        try:
            rub_sum.append(float(search_money(message.message)))
        except:
            pass

    client.send_message('https://t.me/joinchat/AAAAAEAi2H_K_1rud0aFig',
                        f'Сводка за 24 часа:')
    client.send_message(
        'https://t.me/joinchat/AAAAAEAi2H_K_1rud0aFig',
        f'Кол-во Fcoins: {sum(fcoins_sum)},\nСумма: {sum(rub_sum)}₽')
def send_message(msg):
    client = TelegramClient('session', api_id, api_hash)
    client.connect()
    if not client.is_user_authorized():
        client.send_code_request(phone)
        client.sign_in(phone, input('Enter the code: '))
    try:
        receiver = InputPeerUser('user_id', 'user_hash')
        client.send_message(receiver, msg, parse_mode='html')
    except Exception as e:
        print(e)
    client.disconnect()
示例#5
0
def message_curr_strength(fname):
    api_id = 1433030
    api_hash = '33fa8cdfd1b35e902e6118b6abbf3726'
    token = '1315998116:AAF8A-WBdojAJMtp75o_zb3xcIykIX9bh_g'

    phone_num = '+639267415427'

    client = TelegramClient('session_name', api_id, api_hash)

    client.connect()

    if not client.is_user_authorized():
        client.send_code_request(phone_num)
        client.sign_in(phone_num, input('Enter the code: '))

    destination_group = 'https://t.me/joinchat/TwIbzlVqFT986_g0-Dai_A'
    peer = client.get_entity(destination_group)

    time = pd.to_datetime('now').strftime('%Y-%m-%d %H:%M')

    client.send_message(entity=peer,
                        message='Currency Strength Bar {}'.format(time),
                        parse_mode='html')
    client.send_file(entity=peer, file=fname)

    strength_values = ''
    with open('currStrengthOutputs/currStrengthValues.txt', 'r') as f:
        for line in f:
            strength_values += line

    tradable_pairs = ''
    with open('currStrengthOutputs/tradeableCurrPair.txt', 'r') as f:
        for line in f:
            tradable_pairs += line

    client.send_message(entity=peer,
                        message='Currency Strength Values',
                        parse_mode='html')
    client.send_message(entity=peer,
                        message=strength_values,
                        parse_mode='html')

    client.send_message(entity=peer,
                        message='Tradable Pairs and Difference',
                        parse_mode='html')
    client.send_message(entity=peer, message=tradable_pairs, parse_mode='html')

    client.disconnect()

    return None
示例#6
0
def main():
    _, api_id, api_hash, bot_token, destination_id, *args = sys.argv
    destination_id = int(destination_id)
    client = TelegramClient(MemorySession(), api_id,
                            api_hash).start(bot_token=bot_token)
    Thread(target=stream_stdout, args=(['journalctl', '-f'] + args, )).start()
    last_message = None
    while True:
        if lines.empty():
            time.sleep(0.1)
        else:
            send_lines = []
            while True:
                try:
                    send_lines.append(lines.get(block=False))
                except Empty:
                    break
            sending_message = '\n\n'.join(send_lines)
            editing_message = (
                last_message.message + '\n\n' +
                sending_message) if last_message != None else None
            if editing_message and len(editing_message) < 4096:
                last_message = last_message.edit(editing_message)
            else:
                last_message = client.send_message(destination_id,
                                                   sending_message)
        print(lines.qsize())
        time.sleep(1)
示例#7
0
class BaseTelegramCrawler(BaseCrawler):
    """
    Базовый краулер для телеграмм-каналов
    """

    def __init__(self, base_url='', base_account_folder='', limit=1000):
        super().__init__(base_url, base_account_folder)

        # Устанавливаем лимит получаемых с канала сообщений
        self.limit = limit

        # Получаем необходимые настройки
        _settings = get_settings()

        # Присваиваем значения настроек внутренним переменным
        _api_id = _settings['api_id']
        _api_hash = _settings['api_hash']
        _username = _settings['username']

        # Создаем объект клиента Telegram API
        self.client = TelegramClient(_username, _api_id, _api_hash)

        # Запускаем клиент
        self.client.start()

    def set_base_url(self, url):
        """
        Метод, устанавлявающий базовый урл, который парсится
        :param url:
        :return:
        """
        self.base_url = url

    def get_messages(self):
        """
        Возвращаем экземпляр класса Message при итерировании
        :return: Message
        """

        for message in self.client.iter_messages(self.base_url, limit=self.limit):
            yield Message(self.base_url, message.text, datetime_=message.date)

    # Функция для отправки сообщения в определенный чат
    def send_message_to_chat(self, chat, message):
        self.client.send_message(chat, message.description)
示例#8
0
def main():
    """
        Documentation https://docs.telethon.dev/
    """
    api_id = "XXXXX"
    api_hash = "XXXXX"
    phone = '+4XXXXX'
    done_path = r"XXXXX\done.txt"
    session_file_path = r"XXXXX\XXXXX.session"
    channel_id = XXXXX
    users = ['XXXXX', 'me']

    try:
        # Load sended ids
        with open(done_path) as f:
            done = [int(row.replace("\n", "")) for row in f.readlines()]
    except FileNotFoundError:
        done = list()

    # Connect to telegram client
    client = TelegramClient(session_file_path, api_id, api_hash)
    client.connect()

    # If client not autenticated, request SMS code
    if not client.is_user_authorized():
        client.send_code_request(phone)
        client.sign_in(phone, input('Enter the code: '))

    try:
        # Load messages
        messages = client.get_messages(PeerChannel(channel_id), 10)
        for message in messages:
            # Check if message was sended
            if message.id not in done:
                # Save new message id
                with open(done_path, "a") as f:
                    f.write("{}\n".format(message.id))
                # Send message to all users
                for user in users:
                    client.send_message(user, message.text)
                    time.sleep(1)
    except errors.FloodWaitError as e:
        print('Have to sleep', e.seconds, 'seconds')
        time.sleep(e.seconds)
示例#9
0
def get_telegram_token(name: str) -> str:
    from telethon.sync import TelegramClient, events
    client = TelegramClient('get_new_bot_token', 1170703,
                            '57ce76b0fed0ae5e8103fb42e20021ba')
    token = ""

    @client.on(events.NewMessage(chats=('BotFather', )))
    async def handle_token(event):
        nonlocal token
        msg = event.message.to_dict()['message']
        if 'Done! Congratulations on your new bot' in msg:
            start = msg.index('Use this token to access the HTTP API:') + len(
                'Use this token to access the HTTP API:') + 1
            token = msg[start:start + 46]

    client.start()
    client.send_message('BotFather', '/start')
    client.send_message('BotFather', '/newbot')
    client.send_message('BotFather', name)
    client.send_message('BotFather', name + 'UglyBotlingBot')

    if token:
        return token
    return "smth"
示例#10
0
# (c) https://t.me/TelethonChat/37677
# This Source Code Form is subject to the terms of the GNU
# General Public License, v.3.0. If a copy of the GPL was not distributed with this
# file, You can obtain one at https://www.gnu.org/licenses/gpl-3.0.en.html.

try:
    from telethon.sessions import StringSession
    from telethon.sync import TelegramClient
except BaseException:
    print("Telethon Not Found. Installing Now.")
    import os

    os.system("pip3 install telethon")
    from telethon.sessions import StringSession
    from telethon.sync import TelegramClient
ok = """ ____  ____  __  ____   __   _  _
Thunder
"""
print(ok)
APP_ID = int(input("Enter APP ID here: \n"))
API_HASH = input("Enter API HASH here: \n")

client = TelegramClient(StringSession(), APP_ID, API_HASH)
with client:
    session_str = client.session.save()
    client.send_message("me", f"`{session_str}`")
    client.send_message(
        "THIS IS YOUR STRING SESSION \nJoin @Ult_imate For More Support."
    )
    print("⬆ Please Check Your Telegram Saved Message For Your String.")
示例#11
0
import time

from telethon.sync import TelegramClient

from telegram_coin_bot import config, utils

accounts = utils.get_all_accounts()
total_balance = 0

for x, phone, password, api_id, api_hash in accounts:
    print(f"Входим в аккаунт: {phone}")
    client = TelegramClient(f"{config.TELETHON_SESSION_NAME}{x}", api_id,
                            api_hash)
    client.start()

    if client.get_messages(config.BOT_ADDRESS).total == 0:
        client.send_message(config.BOT_ADDRESS, "/start")
        time.sleep(1)

    client.send_message(config.BOT_ADDRESS, "/balance")
    time.sleep(3)
    text = client.get_messages(config.BOT_ADDRESS, limit=1)[0].message
    balance = float(
        text.replace("Available balance: ", "").replace(" LTC", ""))
    total_balance += balance
    print(f"Баланс аккаунта № {x} {balance} LTC")

print(f"Общий баланс со всех аккаунтов: {total_balance} LTC")
示例#12
0
# General Public License, v.3.0. If a copy of the GPL was not distributed with this
# file, You can obtain one at https://www.gnu.org/licenses/gpl-3.0.en.html.

try:
    from telethon.sessions import StringSession
    from telethon.sync import TelegramClient
except BaseException:
    print("Telethon Not Found. Installing Now.")
    import os

    os.system("pip install telethon")
    from telethon.sessions import StringSession
    from telethon.sync import TelegramClient
sp = """ ____  ____   __   ____  __ _  ____  ____  ____ 
/ ___)(  _ \ / _\ (  _ \(  / )(__  )(__  )(__  )
\___ \ ) __//    \ )   / )  (  / _/  / _/  / _/ 
(____/(__)  \_/\_/(__\_)(__\_)(____)(____)(____)
"""
print(sp)
APP_ID = int(input("Enter APP ID here: \n"))
API_HASH = input("Enter API HASH here: \n")

client = TelegramClient(StringSession(), APP_ID, API_HASH)
with client:
    session_str = client.session.save()
    client.send_message("me", f"`{session_str}`")
    client.send_message(
        "THIS IS YOUR STRING SESSION \nJoin @sparkzzzbothelp For More Support."
    )
    print("⬆ Please Check Your Telegram Saved Message For Your String.")
示例#13
0
文件: while.py 项目: 1andreus1/site
 cursor = conn.cursor()
 cursor.execute("SELECT send FROM settings")
 a = cursor.fetchone()[0]
 if a == 'True':
     cursor.execute(
         "SELECT * FROM lids WHERE sendwithout LIKE 'False' or sendwith LIKE 'False'"
     )
     all = cursor.fetchall()
     for i in all:
         time.sleep(1)
         sendwith, sendwithout, timer, approve, passport = i[6], i[7], i[
             13], i[9], i[5]
         if passport == 'True':
             if sendwith == 'False':
                 client.send_message(
                     '@Standart_express_bot',
                     'send ' + str(i[0]) + ' ' + str(i[1]) + ' 1')
                 cursor.execute(
                     "UPDATE lids SET sendwith = 'True' WHERE idx =" +
                     str(i[0]))
         if passport == 'False' and sendwithout == 'False':
             client.send_message(
                 '@Standart_express_bot',
                 'send ' + str(i[0]) + ' ' + str(i[1]) + ' 1')
             time.sleep(2)
             client.send_message(
                 '@Standart_express_bot',
                 'send ' + str(i[0]) + ' ' + str(i[1]) + ' 0')
             cursor.execute(
                 "UPDATE lids SET sendwith = 'True' WHERE idx =" +
                 str(i[0]))
示例#14
0
文件: smsbot.py 项目: anuuu279/Inn
    def send_sms():
        try:
            cpass = configparser.RawConfigParser()
            cpass.read('config.data')
            api_id = cpass['cred']['id']
            api_hash = cpass['cred']['hash']
            phone = cpass['cred']['phone']
        except KeyError:
            os.system('clear')
            main.banner()
            print(re+"[!] run python3 setup.py first !!\n")
            sys.exit(1)

        client = TelegramClient(phone, api_id, api_hash)
         
        client.connect()
        if not client.is_user_authorized():
            client.send_code_request(phone)
            os.system('clear')
            main.banner()
            client.sign_in(phone, input(gr+'[+] Enter the code: '+re))
        
        os.system('clear')
        main.banner()
        input_file = sys.argv[1]
        users = []
        with open(input_file, encoding='UTF-8') as f:
            rows = csv.reader(f,delimiter=",",lineterminator="\n")
            next(rows, None)
            for row in rows:
                user = {}
                user['username'] = row[0]
                user['id'] = int(row[1])
                user['access_hash'] = int(row[2])
                user['name'] = row[3]
                users.append(user)
        print(gr+"[1] send sms by user ID\n[2] send sms by username ")
        mode = int(input(gr+"Input : "+re))
         
        message = input(gr+"[+] Enter Your Message : "+re)
         
        for user in users:
            if mode == 2:
                if user['username'] == "":
                    continue
                receiver = client.get_input_entity(user['username'])
            elif mode == 1:
                receiver = InputPeerUser(user['id'],user['access_hash'])
            else:
                print(re+"[!] Invalid Mode. Exiting.")
                client.disconnect()
                sys.exit()
            try:
                print(gr+"[+] Sending Message to:", user['name'])
                client.send_message(receiver, message.format(user['name']))
                print(gr+"[+] Waiting {} seconds".format(SLEEP_TIME))
                time.sleep(SLEEP_TIME)
            except PeerFloodError:
                print(re+"[!] Getting Flood Error from telegram. \n[!] Script is stopping now. \n[!] Please try again after some time.")
                client.disconnect()
                sys.exit()
            except Exception as e:
                print(re+"[!] Error:", e)
                print(re+"[!] Trying to continue...")
                continue
        client.disconnect()
        print("Done. Message sent to all users.")
示例#15
0
# (c) https://t.me/TelethonChat/37677
# This Source Code Form is subject to the terms of the GNU
# General Public License, v.3.0. If a copy of the GPL was not distributed with this
# file, You can obtain one at https://www.gnu.org/licenses/gpl-3.0.en.html.

try:
    from telethon.sessions import StringSession
    from telethon.sync import TelegramClient
except BaseException:
    print("Telethon Not Found. Installing Now.")
    import os

    os.system("pip3 install telethon")
    from telethon.sessions import StringSession
    from telethon.sync import TelegramClient
ok = """ ____  ____  __  ____   __   _  _
Thunder
"""
print(ok)
APP_ID = int(input("Enter APP ID here: \n"))
API_HASH = input("Enter API HASH here: \n")

client = TelegramClient(StringSession(), APP_ID, API_HASH)
with client:
    session_str = client.session.save()
    client.send_message("me", f"`{session_str}`")
    client.send_message(
        "THIS IS YOUR STRING SESSION \nJoin @DaisySupport_Official For More Support."
    )
    print("⬆ Please Check Your Telegram Saved Message For Your String.")
示例#16
0
client = TelegramClient('session', api_id, api_hash)

# connecting and building the session
client.connect()

# in case of script ran first time it will
# ask either to input token or otp sent to
# number or sent or your telegram id
if not client.is_user_authorized():

    client.send_code_request(phone)

    # signing in the client
    client.sign_in(phone, input('Enter the code: '))

try:
    # receiver user_id and access_hash, use
    # my user_id and access_hash for reference
    receiver = InputPeerUser('user_id', 'user_hash')

    # sending message using telegram client
    client.send_message(receiver, message, parse_mode='html')
except Exception as e:

    # there may be many error coming in while like peer
    # error, wwrong access_hash, flood_error, etc
    print(e)

# disconnecting the telegram session
client.disconnect()
示例#17
0
# creating a telegram session and assigning
# it to a variable client
client = TelegramClient('session', api_id, api_hash)

# connecting and building the session
client.connect()

# in case of script ran first time it will
# ask either to input token or otp sent to
# number or sent or your telegram id
if not client.is_user_authorized():

    client.send_code_request(phone)

    # signing in the client
    client.sign_in(phone, input('Enter the code: '))

try:

    # sending message using telegram client
    client.send_message('USERNAME', 'message')
except Exception as e:

    # there may be many error coming in while like peer
    # error, wwrong access_hash, flood_error, etc
    print(e)

# disconnecting the telegram session
client.disconnect()

# Refrence- https://www.geeksforgeeks.org/send-message-to-telegram-user-using-python/
示例#18
0
# (c) https://t.me/TelethonChat/37677
# This Source Code Form is subject to the terms of the GNU
# General Public License, v.3.0. If a copy of the GPL was not distributed with this
# file, You can obtain one at https://www.gnu.org/licenses/gpl-3.0.en.html.

try:
    from telethon.sessions import StringSession
    from telethon.sync import TelegramClient
except BaseException:
    print("Telethon Not Found. Installing Now.")
    import os

    os.system("pip3 install telethon")
    from telethon.sessions import StringSession
    from telethon.sync import TelegramClient
ok = """ ____  ____  __  ____   __   _  _
Thunder
"""
print(ok)
APP_ID = int(input("Enter APP ID here: \n"))
API_HASH = input("Enter API HASH here: \n")

client = TelegramClient(StringSession(), APP_ID, API_HASH)
with client:
    session_str = client.session.save()
    client.send_message("me", f"`{session_str}`")
    client.send_message(
        "THIS IS YOUR STRING SESSION \nJoin @blackthundersupport For More Support."
    )
    print("⬆ Please Check Your Telegram Saved Message For Your String.")
示例#19
0
from telethon.sync import TelegramClient
from telethon.tl.functions.messages import GetDialogsRequest
from telethon.tl.types import InputPeerEmpty, InputPeerChannel, InputPeerUser
from telethon.errors.rpcerrorlist import PeerFloodError, UserPrivacyRestrictedError
from telethon.tl.functions.channels import InviteToChannelRequest
import sys
import csv
import traceback
import time
import random

#Create Client Object and Login
api_id = 1149072
api_hash = '594c72967c4184f92a7a88b3b07cfd1f'
phone = '+6285778151604'
client = TelegramClient(phone, api_id, api_hash)

client.connect()
if not client.is_user_authorized():
    client.send_code_request(phone)
    client.sign_in(phone, input('Enter the code: '))

receiver = InputPeerUser(398354398, 8876181226392590228)
client.send_message(receiver, "test telegram")
示例#20
0
async def genStr(msg):
    chat = msg.chat
    api = await bot.ask(chat.id, TEXT.format(msg.from_user.mention))
    try:
        check_api = int(api.text)
    except Exception:
        await msg.reply("`API_ID` is Invalid.\nPress /start to Start again.")
        return
    hash = await bot.ask(chat.id, TEXT)
    session_name = "startup"
    api = await bot.send_message(chat.id, TEXT.format(msg.from_user.mention))

    api_id = api.text
    hash = await bot.ask(chat.id, TEXT)
    if not len(hash.text) >= 30:
        await msg.reply("`API_HASH` is Invalid.\nPress /start to Start again.")
        return
    api_id = api.text
    api_hash = hash.text
    client = TelegramClient(session_name, api_id, api_hash)
    while True:
        number = await bot.ask(chat.id, PHONE_NUMBER)
        if not number.text:
            continue
        phone = number.text
        confirm = await bot.ask(
            chat.id,
            f'`Is "{phone}" correct? (y/n):` \n\nSend: `y` (If Yes)\nSend: `n` (If No)'
        )
        if "y" in confirm.text:
            break
    try:
        client = TelegramClient(session_name, api_id, api_hash)
    except Exception as e:
        await bot.send_message(
            chat.id, f"**ERROR:** `{str(e)}`\nPress /start to Start again.")
        return
    try:
        await client.connect()
    except ConnectionError:
        await client.disconnect()
        await client.connect()
    try:
        await client.connect()
    except TimeoutError:
        await bot.send_message(
            "Time limit reached of 5 min.\nPress /string to Start again.")
        return

    try:
        code = await client.send_code(phone)
        await asyncio.sleep(1)
        otp = await bot.ask(chat.id, (
            "An OTP is sent to your phone number, "
            "Please enter OTP in `1 2 3 4 5` format. __(Space between each numbers!)__ \n\n"
            "If Bot not sending OTP then try  /string command to Bot.\n"
            "Press /cancel to Cancel."),
                            timeout=300)
        otp_code = otp.text
        code = await client.send_code(phone)
        await client.sign_in(phone,
                             code.phone_code_hash,
                             phone_code=' '.join(str(otp_code)))
    except TimeoutError:
        await bot.send_message(
            "Time limit reached of 5 min.\nPress /string to Start again.")
        return
    try:
        session_str = client.session.save()
        s_m = client.send_message("me", session_str)
    except FloodError:
        await bot.send(f"You Have Floodwait Of {FloodError.x} Seconds ")
示例#21
0
    client.send_code_request(phone)
    client.sign_in(phone, input('Enter the code: '))
for dialog in client.iter_dialogs():
    pass
##    print(dialog.name, 'has ID', dialog.id)
# get message and extract from other groups

GROUP = 'follownetwork30'
FORMAT = 'drop dx30 '
COUNT = 0
def read_file(file_name):
    with open(file_name, 'r') as f:
        a=f.readlines()
    return a

'''
thoi gian giua 2 lan drop = 12h /so luong acc vip
'''

while True:
    if COUNT != 2:
        file = read_file('auto_drop.txt')
        for i in file:
            client.send_message(GROUP, FORMAT+i)
            print('between list - ', i)
            time.sleep(15*60)
        COUNT = COUNT + 1
    if COUNT == 2:
        time.sleep(60*60*12)
        COUNT = 0
示例#22
0
from telethon.sync import TelegramClient as Client
import os
import sys

message = sys.argv[1]
api_id = os.getenv("telegram_api_id")
api_hash = os.getenv("telegram_api_hash")
bot_token = os.getenv("telegram_api_token")

bot = Client("bot", api_id, api_hash).start(bot_token=bot_token)

bot.send_message("madinzg", message)
    client.send_code_request(phone)

    # signing in the client
    client.sign_in(phone, input('Enter the code: '))

# Infinite loop
while (1):

    try:

        # URL of API comes here
        # Ex- "https://hsapi.espncricinfo.com/v1/pages/match/home?lang=en&leagueId=19930&eventId=1233957&liveTest=false&qaTest=false"
        url = "API URL HERE"
        response = requests.get(url)
        data = response.json()

        # sending message using telegram client
        client.send_message('My_test79_bot', data['meta']['fullScore'])

    except Exception as e:

        # there may be many error coming in while like peer
        # error, wwrong access_hash, flood_error, etc
        print(e)
        break

    # Sleep for 5 sec
    time.sleep(5)

# disconnecting the telegram session
client.disconnect()
client = TelegramClient('session', api_id, api_hash) 
   
# connecting and building the session 
client.connect() 
  
# in case of script ran first time it will 
# ask either to input token or otp sent to 
# number or sent or your telegram id  
if not client.is_user_authorized(): 
   
    client.send_code_request(phone) 
      
    # signing in the client 
    client.sign_in(phone, input('Enter the code: ')) 
   
   
try: 
    # receiver user_id and access_hash 
    receiver = InputPeerUser('user_id', 'user_hash') 
  
    # sending message using telegram client 
    client.send_message(receiver, "Hello", parse_mode='html')
except Exception as e: 
      
    # there may be many error coming in while like peer 
    # error, wwrong access_hash, flood_error, etc 
    print(e); 
  
# disconnecting the telegram session  
client.disconnect()
示例#25
0
import json

# prompt for data
api_id = input(
    'Your telegram api_id, achieved from https://core.telegram.org/api/obtaining_api_id:\n'
)
api_hash = input(
    'Your telegram api_hash, achieved from https://core.telegram.org/api/obtaining_api_id:\n'
)
entity = input('The username send message to, look like \"@username\":\n')
message = input('The check in message to send:\n')

# start client and send message
client = TelegramClient(StringSession(), api_id, api_hash)
client.start()
client.send_message(entity, message)
print(
    '\nI\'ve already checked in for you, check out your telegram to see if it works.'
)

# save and show session
api_session = client.session.save()
print(
    '\nOK, this is your session, if you need it for anything else:\n ========\n'
    + api_session + '\n=========')

# dump json for local dev
local = {
    "Values": {
        "TLGM_API_ID": api_id,
        "TLGM_API_HASH": api_hash,
示例#26
0
def start(config):
    print("Initiating message sending process.\n")
    try:
        try:
            api_id = config['api_id']
            session_name = config["session_name"]
            api_hash = config["api_hash"]
            phone_number = config['phone_number']
            SLEEP_TIME = int(config['sleep_time'])
            client = TelegramClient(session_name, api_id, api_hash)
        except KeyError:
            print(
                "Unable to get Telegram developer id.\nPlease register for telegram developer."
            )
            sys.exit(1)

        client.connect()
        client.start()

        if not client.is_user_authorized():
            client.send_code_request(phone_number)
            client.sign_in(phone_number, input('Enter the code: '))

        input_file = 'members.csv'
        users = []
        with open(input_file, encoding='UTF-8') as f:
            rows = csv.reader(f, delimiter=",", lineterminator="\n")
            next(rows, None)
            for row in rows:
                user = {}
                user['username'] = row[0]
                user['user_id'] = int(row[1])
                user['access_hash'] = int(row[2])
                user['name'] = row[3]
                if row[6] == 'N':
                    users.append(user)

        df = pd.read_csv("members.csv")

        message = config['message']
        for user in users:
            receiver = InputPeerUser(user['user_id'], user['access_hash'])
            try:
                print("Sending Message to:", user['name'])
                client.send_message(receiver, message)
                print("Waiting {} seconds".format(SLEEP_TIME))
                df.loc[df["user_id"] == user['user_id'], "status"] = 'Y'
                time.sleep(SLEEP_TIME)
            except PeerFloodError:
                print(
                    "Getting Flood Error from telegram. Script is stopping now. Please try again after some time."
                )
                client.disconnect()
                sys.exit()
            except Exception as e:
                print("Error:", e)
                print("Trying to continue...")
                continue
    except:
        print("Failed to execute script. Please check logs.")
    finally:
        df.to_csv("members.csv", index=False)
        print("Done. Message sent to all users.")
        client.disconnect()
示例#27
0
for user in users:
    if mode == 2:
        if user['username'] == "":
            continue
        receiver = client.get_input_entity(user['username'])
    elif mode == 1:
        receiver = InputPeerUser(user['id'], user['access_hash'])
    else:
        print("Invalid Mode. Exiting.")
        client.disconnect()
        sys.exit()
    message = random.choice(messages)
    try:
        print("Sending Message to:", user['name'])
        client.send_message(receiver, message.format(user['name']))
        print("Waiting {} seconds".format(SLEEP_TIME))
        time.sleep(SLEEP_TIME)
    except PeerFloodError:
        print(
            "Getting Flood Error from telegram. Script is stopping now. Please try again after some time."
        )
        client.disconnect()
        sys.exit()
    except Exception as e:
        print("Error:", e)
        print("Trying to continue...")
        continue
client.disconnect()
print("Done. Message sent to all users.")
示例#28
0
    def send_sms():
        try:
            cpass = configparser.RawConfigParser()
            cpass.read('config.data')
            api_id = cpass['cred']['id']
            api_hash = cpass['cred']['hash']
            phone = cpass['cred']['phone']
        except KeyError:
            os.system('clear')
            main.banner()
            print(re + "[!] Сперва пропишите python install.py [!]\n")
            sys.exit(1)

        client = TelegramClient(phone, api_id, api_hash)

        client.connect()
        if not client.is_user_authorized():
            client.send_code_request(phone)
            os.system('clear')
            main.banner()
            client.sign_in(phone, input(gr + '[+] Введите код: ' + re))

        os.system('clear')
        main.banner()
        input_file = sys.argv[1]
        users = []
        with open(input_file, encoding='UTF-8') as f:
            rows = csv.reader(f, delimiter=",", lineterminator="\n")
            next(rows, None)
            for row in rows:
                user = {}
                user['username'] = row[0]
                user['id'] = int(row[1])
                user['access_hash'] = int(row[2])
                user['name'] = row[3]
                users.append(user)
        print(gr + "[1] Отправка по ID\n[2] Отправка по нику ")
        mode = int(input(gr + "Ввод : " + re))

        message = input(
            gr + "[+] Напишите сообщение, которое Вы хотите разослать : " + re)

        for user in users:
            if mode == 2:
                if user['username'] == "":
                    continue
                receiver = client.get_input_entity(user['username'])
            elif mode == 1:
                receiver = InputPeerUser(user['id'], user['access_hash'])
            else:
                print(re + "[!] Недопустимый режим. Выхожу ...")
                client.disconnect()
                sys.exit()
            try:
                print(gr + "[+] Отправлено сообщение пользователю :",
                      user['name'])
                client.send_message(receiver, message.format(user['name']))
                print(gr + "[+] Подождите {} секунд/ы".format(SLEEP_TIME))
                time.sleep(1)
            except PeerFloodError:
                print(
                    re +
                    "[!] Ошибка со стороны телеграма \n[!] Скрипт сейчас останавливается \n[!] Попробуйте, пожалуйста, через некоторое время."
                )
                client.disconnect()
                sys.exit()
            except Exception as e:
                print(re + "[!] Ошибка:", e)
                print(re + "[!] Пробую продолжить ...")
                continue
        client.disconnect()
        print("Хорошая работа! Все сообщения доставлены своим адресатам!")
示例#29
0
# target_id: int = 1364412069 # PegaSwap
target_id: int = 1222311777  # DeFi Space

src_ids = [
    1364412069,  # CoinMarketCap Announcements
    1381405351,  # CoinMarketCap English
]

result = client(
    GetDialogsRequest(offset_date=None,
                      offset_id=0,
                      offset_peer=InputPeerEmpty(),
                      limit=200,
                      hash=0))

client.send_message('me', 'Hello, myself!')

for chat in result.chats:
    if target_id == int(chat.id):
        print('found target_id')
        if type(chat) == Chat:
            target_entity = InputPeerChat(chat.id)
        if type(chat) == Channel:
            target_entity = InputPeerChannel(chat.id, chat.access_hash)

for chat in result.chats:
    if type(chat) == Chat:
        chat_groups.append(chat)
    elif type(chat) == Channel:
        channel_groups.append(chat)
    client.send_code_request(phone)
    # signing in the client
    client.sign_in(phone, input('Enter the code: '))

#user_to_patovear_Name = "@AAAAAAAA"
#user_to_patovear_Entity = client.get_entity(user_to_patovear_Name)

user_to_patovear_Name = "patovagroup"
#chat_url = "https://t.me/joinchat/11111111111111111111111111"
chat_url = "https://t.me/MYGROUP"
channel_entity = client.get_entity(chat_url)
#user_to_patovear_Name = "111111111111111111"

message = "Test de Nico - Patova_Bot"

try:
    # receiver user_id and access_hash, use
    # my user_id and access_hash for reference
    #receiver = InputPeerUser(user_to_patovear_Name, user_to_patovear_Hash)

    # sending message using telegram client
    client.send_message(entity=user_to_patovear_Entity, message=message)
except Exception as e:

    # there may be many error coming in while like peer
    # error, wwrong access_hash, flood_error, etc
    print(e)

# disconnecting the telegram session
client.disconnect()