Beispiel #1
0
def main():
    session_name = environ.get('TG_SESSION', 'session')
    client = TelegramClient(session_name,
                            int(environ['TG_API_ID']),
                            environ['TG_API_HASH'],
                            proxy=None,
                            update_workers=4,
                            spawn_read_thread=False)

    if 'TG_PHONE' in environ:
        client.start(phone=environ['TG_PHONE'])
    else:
        client.start()

    client.add_event_handler(update_handler)
    print('(Press Ctrl+C to stop this)')
    client.idle()
Beispiel #2
0
            if trigger in words:
                # Remove recent replies older than 10 minutes
                recent_reacts[to_id] = [
                    a for a in recent_reacts[to_id] if
                    datetime.now() - a < timedelta(minutes=10)
                ]
                # Send a reaction as a reply (otherwise, event.respond())
                event.reply(response)
                # Add this reaction to the list of recent actions
                recent_reacts[to_id].append(datetime.now())

        # Automatically send relevant media when we say certain things
        # When invoking requests, get_input_entity needs to be called manually
        if event.out:
            if event.raw_text.lower() == 'x files theme':
                client.send_voice_note(event.message.to_id, 'xfiles.m4a',
                                       reply_to=event.message.id)
            if event.raw_text.lower() == 'anytime':
                client.send_file(event.message.to_id, 'anytime.png',
                                 reply_to=event.message.id)
            if '.shrug' in event.text:
                event.edit(event.text.replace('.shrug', r'¯\_(ツ)_/¯'))

    if 'TG_PHONE' in environ:
        client.start(phone=environ['TG_PHONE'])
    else:
        client.start()

    print('(Press Ctrl+C to stop this)')
    client.idle()
Beispiel #3
0
    soup = BeautifulSoup(page, "html.parser")
    for anchor in soup.find_all("div", {"class": "content corner"}):
        transcripts = anchor.find("div", {"itemprop": "transcript"})
        if not transcripts:
            continue
        transcript = transcripts.get_text()
        # print(transcript)
        audio_files = anchor.find_all("source")
        ogg_file = BASE_URL + audio_files[1].get("src")
        # print(ogg_file)
        local_file = DownLoadFile(ogg_file)
        # convert using FFMpeg
        shell_command = "ffmpeg -i " + local_file + " -map 0:a -codec:a libopus -b:a 100k -vbr on " + local_file + ".opus"
        r = os.system(shell_command)
        upload_response = client.send_file(UPLOAD_GRP_ENTITY,
                                           local_file + ".opus",
                                           allow_cache=False,
                                           voice_note=True)
        # print(upload_response.id)
        client.send_message(UPLOAD_GRP_ENTITY,
                            transcript,
                            reply_to=upload_response.id)
        # now remove the file
        os.remove(local_file)
        os.remove(local_file + ".opus")

# ends with Ctrl+C
client.idle()
# Call .disconnect() when you're done
# client.disconnect()
Beispiel #4
0
def main():
    global kaipa
    global bot
    global botid
    global otryad
    global oratorID

    client = TelegramClient("bot",
                            243918,
                            '2ace13b37b702eb5407964ff753fc37d',
                            spawn_read_thread=False,
                            update_workers=1)
    client.start()

    local_tz = pytz.timezone('Europe/Moscow')

    def mess(messag):
        client.send_message(bot, messag)

    def utc_to_local(utc_dt):
        local_dt = utc_dt.replace(tzinfo=pytz.utc).astimezone(local_tz)
        return local_tz.normalize(local_dt)

    @client.on(events.NewMessage)
    def attack(update):
        global lastpin
        global lastgold
        if update.message.from_id == oratorID and update.message.to_id == otryad:
            theMessage = update.message.message
            if "⚔️🖤" in theMessage:
                lastpin = "🖤"
                sleep(random.randint(1, 2))
                client.send_message(bot, "⚔Атака")
            elif "⚔️☘️" in theMessage:
                lastpin = "☘️"
                sleep(random.randint(1, 2))
                client.send_message(bot, "⚔Атака")
            elif "⚔️🍁" in theMessage:
                lastpin = "🍁"
                sleep(random.randint(1, 2))
                client.send_message(bot, "⚔Атака")
            elif "⚔️🐢" in theMessage:
                lastpin = "🐢"
                sleep(random.randint(1, 2))
                client.send_message(bot, "⚔Атака")
            elif "⚔️🦇" in theMessage:
                lastpin = "🦇"
                sleep(random.randint(1, 2))
                client.send_message(bot, "⚔Атака")
            elif "⚔️🍆" in theMessage:
                lastpin = "🍆"
                sleep(random.randint(1, 2))
                client.send_message(bot, "⚔Атака")
            elif "⚔️🌹" in theMessage:
                lastpin = "🌹"
                sleep(random.randint(1, 2))
                client.send_message(bot, "⚔Атака")

        if "Сводки с полей" in update.message.message:
            sleep(random.randint(10, 16))
            client.send_message(bot, "/report")

        if "Смелый вояка!" in update.message.message:
            print(lastpin)
            sleep(random.randint(1, 2))
            mess(lastpin)
            lastpin = "🦇"

        if "/go" in update.message.message:
            sleep(random.randint(7, 15))
            client.send_message(bot, "/go")

        if update.message.from_id == kaipa and "#les" in update.message.message:
            number_of = update.message.message.split()
            les(int(number_of[0]))

        if update.message.from_id == botid and "Твои результаты в бою" in update.message.message:
            print(update.message.message)
            sleep(random.randint(3, 5))
            client(
                ForwardMessagesRequest(from_peer=client.get_entity(
                    PeerUser(botid)),
                                       id=[update.message.id],
                                       to_peer=client.get_entity(otryad)))

        if update.message.message == "Выносливость восстановлена: ты полон сил. Вперед, на поиски приключений!":
            if utc_to_local(datetime.utcnow()).hour > 1 and utc_to_local(
                    datetime.utcnow()).hour < 7:
                corovan(2)
            else:
                les(3)

        if update.message.message == "test":
            threading.Timer(random.randint(2, 3), mess, ["🏅Герой"]).start()

        #if "⚖️Exchange slot: Stick" in update.message.message:
        #if lastgold != 0:
        #comm = update.message.message.split(" ")
        #sleep(1)
        #mess(min(lastgold, comm[8]))

        #if "Битва семи замков через" in update.message.message:
        #comm = update.message.message.split("\n")
        #gold = comm[10].split("💰")
        #lastgold = int(gold[1])
        #print(lastgold)

    def les(num):
        if num > 0:
            threading.Timer(random.randint(1, 4), mess, ["🗺Квесты"]).start()
            threading.Timer(random.randint(5, 7), mess, ["🌲Лес"]).start()
            threading.Timer(random.randint(480, 600), les, [num - 1]).start()

    def corovan(num):
        if num > 0:
            sleep(random.randint(1, 5))
            client.send_message(bot, "🗺Квесты")
            sleep(random.randint(2, 4))
            client.send_message(bot, "🗡ГРАБИТЬ КОРОВАНЫ")
            sleep(random.randint(480, 600))
            corovan(num - 1)

    client.idle()
Beispiel #5
0
class Client(object):
    def __init__(self, account):
        self.account = account
        telegram = self.account.apis.telegram
        api_id = telegram['api_id']
        api_hash = telegram['api_hash']
        self.instance = TelegramClient(self.account.name,
                                       api_id,
                                       api_hash,
                                       proxy=const.Proxy,
                                       update_workers=4,
                                       spawn_read_thread=True)
        self.dispatch = Dispatch(self)

    def getMessages(self, target: str):
        return self.dispatch.excute(
            Command.from_dict(name='getMessages', target=target))

    def joinChannel(self, target: str):
        return self.dispatch.excute(
            Command.from_dict(name='joinChannel', target=target))

    def sendMessage(self, target: str, msg: str):
        return self.dispatch.excute(
            Command.from_dict(name='sendMessage', target=target, para=[msg]))

    def OnMessage(self, event):
        command = Command(event.raw_text)
        if command.mobile and command.mobile != self.account.mobile:  # 如果命令中指定手机号,则在指定手机号中执行命令
            return
        if str(event.chat.phone) == const.TelegramPhone:
            logger.debug('{}: {}'.format(self.account.mobile, event.raw_text))
        try:
            return self.dispatch.excute(command)
        except Exception:
            logError()
        return ''

    @classmethod
    def create(cls, account, index=''):
        self = cls(account)
        if index:
            index = '第{}个账号'.format(index)
        logger.debug('开始登陆:\n{}'.format(self.account, index))
        self.instance.start()
        self.dispatch.joinMyChannel()
        self.instance.on(events.NewMessage)(self.OnMessage)
        logger.debug('登陆完成')
        return self

    @classmethod
    def bulkCreate(cls, accounts):
        clients = []
        for index, account in enumerate(accounts):
            clients.append(cls.create(account, index))
            time.sleep(0.2)
        logger.debug('初始化完成客户端: {}个'.format(len(accounts)))
        return clients

    def forever(self):
        try:
            self.instance.idle()
        except KeyboardInterrupt:
            self.instance.disconnect()