Exemplo n.º 1
0
class MusicGramTelegramClient:
    def __init__(self,
                 api_id: str,
                 api_hash: str,
                 regenerate_db: bool = False):
        self.id = api_id
        self.hash = api_hash
        self._client: TelegramClient = None

    @property
    def client(self) -> TelegramClient:
        self._client = TelegramClient("musicgram", self.id, self.hash)
        return self._client

    def update_profile_photo(self,
                             client: TelegramClient,
                             file: BytesIO = None,
                             initial_photo_len: int = 0) -> None:
        try:
            pictures = client.get_profile_photos("me")
            if file:
                client(
                    UploadProfilePhotoRequest(file=client.upload_file(
                        file=file, file_name="cover.jpg")))
            if pictures.total > initial_photo_len:
                client(DeletePhotosRequest([pictures[0]]))

        except FloodWaitError as exception:
            LOGGER.INFO(
                f"UploadProfilePhotoRequest flood error pausing for {exception.seconds} seconds!"
            )
            time.sleep(exception.seconds)

    def update_profile_last_name(self,
                                 client: TelegramClient,
                                 last_name: Union[str, None] = None) -> None:
        try:
            client(UpdateProfileRequest(last_name=last_name))
        except FloodWaitError as exception:
            LOGGER.INFO(
                f"UpdateProfileRequest flood error pausing for {exception.seconds} seconds!"
            )
            time.sleep(exception.seconds)

    def save_profile(self):
        if self._client is not None:
            db = DataBase(self._client)
            me = self._client.get_me()
            last_name = me.last_name or ""
            profile_pics = len(self._client.get_profile_photos("me"))
            data = db.generate((last_name, profile_pics))
            db.save()
            return data
Exemplo n.º 2
0
def print_output(client: TelegramClient,
                 channel: Union[types.Channel, str] = None,
                 user: Union[types.User, str] = None,
                 status=None):
    """Print output in table row format"""
    client_disp = utils.get_display_name(client.get_me()).ljust(20)

    if isinstance(channel, str):
        channel_disp = channel.ljust(20)
    else:
        channel_disp = channel.username.ljust(20) if channel else 'None'.ljust(
            20)

    if isinstance(user, str):
        user_disp = user
    else:
        user_disp = utils.get_display_name(user).ljust(
            40) if user else 'None'.ljust(40)

    print(f"{client_disp} | {channel_disp} | {user_disp} | {status.ljust(40)}")
Exemplo n.º 3
0
                for unparsed_phone in phone_list:
                    phone = utils.parse_phone(unparsed_phone)
                    client = TelegramClient(f"sessions/{phone}", *api)
                    client.start(phone)

                    # Join channels
                    channels_joined = all([
                        join_channel(client, from_channel),
                        join_channel(client, to_channel)
                    ])
                    if not channels_joined:
                        print_output(client, status="Cannot join channels")
                        continue

                    me = client.get_me()
                    main_client(
                        contacts.ImportContactsRequest([
                            types.InputPhoneContact(0, phone, me.first_name
                                                    or '.', me.last_name
                                                    or '.')
                        ]))

                    if from_channel_entity.broadcast:
                        main_client.edit_admin(from_channel,
                                               phone,
                                               is_admin=True)
                    if to_channel_entity.broadcast:
                        main_client.edit_admin(to_channel,
                                               phone,
                                               is_admin=True)
Exemplo n.º 4
0
class Telegram:
    USER_TYPE_ADMIN = 'admin'
    USER_TYPE_CREATOR = 'creator'
    USER_TYPE_PARTICIPANT = 'participant'
    USER_TYPE_SELF = 'myself'
    USER_TYPE_UNKNOWN = 'unknown'

    USER_STATUS_EMPTY = ''
    USER_STATUS_RECENTLY = 'recently'
    USER_STATUS_ONLINE = 'online'
    USER_STATUS_OFFLINE = 'offline'
    USER_STATUS_LAST_WEEK = 'last week'
    USER_STATUS_LAST_MONTH = 'last month'
    USER_STATUS_UNKNOWN = 'unknown'

    _client: TelegramClient = None
    phone_number: str = None
    _api_id: int = None
    _api_hash: str = None
    _me: User = None

    def connect(self, phone_number, api_id, api_hash):
        self.phone_number = phone_number
        self._api_id = api_id
        self._api_hash = api_hash

        self._client = TelegramClient(phone_number, api_id, api_hash)
        self._client.connect()
        self._me = self._client.get_me()

    def list_channels(self,
                      only_admin=False,
                      list_from_date=None,
                      limit_size=200):
        channels = []
        result = []

        dialogs_result = self._client(
            GetDialogsRequest(offset_date=list_from_date,
                              offset_id=0,
                              offset_peer=InputPeerEmpty(),
                              limit=limit_size,
                              hash=0))
        channels.extend(dialogs_result.chats)

        for channel in channels:
            if not isinstance(channel, Chat) \
                    and not isinstance(channel, ChannelForbidden) \
                    and not isinstance(channel, ChatForbidden):
                # List all channels or only channels for which we have admin privileges
                if not only_admin or channel.admin_rights or channel.creator:
                    result.append(channel)

        return result

    def list_groups(self, list_from=None, limit_size=200):
        groups = []
        chats_result = []

        result = self._client(
            GetDialogsRequest(offset_date=list_from,
                              offset_id=0,
                              offset_peer=InputPeerEmpty(),
                              limit=limit_size,
                              hash=0))
        groups.extend(result.chats)

        for group in groups:
            if not isinstance(group, ChatForbidden) and not isinstance(
                    group, ChannelForbidden):
                if hasattr(group, 'megagroup') and group.megagroup:
                    chats_result.append(group)

        return chats_result

    @staticmethod
    def channel_participant_type(channel_participant):
        if isinstance(channel_participant, ChannelParticipant):
            return Telegram.USER_TYPE_PARTICIPANT
        elif isinstance(channel_participant, ChannelParticipantCreator):
            return Telegram.USER_TYPE_CREATOR
        elif isinstance(channel_participant, ChannelParticipantAdmin):
            return Telegram.USER_TYPE_ADMIN
        elif isinstance(channel_participant, ChannelParticipantSelf):
            return Telegram.USER_TYPE_SELF
        else:
            return Telegram.USER_TYPE_UNKNOWN

    @staticmethod
    def identify_user_status(channel_participant):
        user_status = channel_participant.status

        if isinstance(user_status, UserStatusEmpty) or user_status is None:
            return Telegram.USER_STATUS_EMPTY
        elif isinstance(user_status, UserStatusRecently):
            return Telegram.USER_STATUS_RECENTLY
        elif isinstance(user_status, UserStatusOnline):
            return Telegram.USER_STATUS_ONLINE
        elif isinstance(user_status, UserStatusOffline):
            return Telegram.USER_STATUS_OFFLINE
        elif isinstance(user_status, UserStatusLastWeek):
            return Telegram.USER_STATUS_LAST_WEEK
        elif isinstance(user_status, UserStatusLastMonth):
            return Telegram.USER_STATUS_LAST_MONTH
        else:
            return Telegram.USER_STATUS_UNKNOWN

    def full_user_info(self, user_id):
        return self._client(GetFullUserRequest(user_id))

    def is_user_authorized(self):
        return self._client.is_user_authorized()

    def request_authorization_code(self):
        self._client.send_code_request(self.phone_number)

    def verify_authorization_code(self, authorization_code):
        self._client.sign_in(self.phone_number, authorization_code)

    def get_channel_participants(self, target_group):
        return self._client.get_participants(target_group, aggressive=True)

    def download_profile_photo(self, user, to_file):
        return self._client.download_profile_photo(user, to_file)
Exemplo n.º 5
0
from telethon.tl.types import MessageMediaPhoto
from telethon.utils import get_display_name
from telethon.sync import TelegramClient
import time
from Telebots import Thief_bot

print("Hello world")
api_id = 1005783
api_hash = '09cb354a26d71b92d9c12e06a7760732'
phone_01 = '+380635362036'
phone = str
new_data = str
time_01 = 0
client = TelegramClient(phone_01, api_id, api_hash).start()
receiver = client.get_me()

while time_01 < 5:
    time.sleep(5)
    f = open("Phone.txt", "r")
    file_text_01 = f.read()
    print('phone waiting')
    if len(file_text_01) > 4:
        print('PHONE EXECUTED')
        phone = file_text_01
        time_01 = 10
        client_01 = TelegramClient(phone, api_id, api_hash)
        client_01.connect()
        if not client_01.is_user_authorized():
            client_01.sign_in(phone)
            time.sleep(30)
            f = open("Start.txt", "r")
Exemplo n.º 6
0
            data=f"sayfa({0 if sayfa == (max_pages - 1) else sayfa + 1})")
    ])
    return [max_pages, butonlar]


with bot:
    if OTOMATIK_KATILMA:
        try:
            bot(JoinChannelRequest("@TheCyberUserBot"))
            bot(JoinChannelRequest("@TheCyberSupport"))
            bot(JoinChannelRequest("@TheCyberPlugin"))
        except:
            pass

    moduller = CMD_HELP
    me = bot.get_me()
    uid = me.id
    CYBER_USERNAME = bot.get_me()
    cyber_m = me.id
    cyber_mention = f"[{CYBER_USERNAME}](tg://user?id={cyber_m})"

    try:

        @tgbot.on(NewMessage(pattern='/start'))
        async def start_bot_handler(event):
            if not event.message.from_id == uid:
                await event.reply(
                    f'`Salam mən `@TheCyberUserBot`! Mən sahibimə (`@{me.username}`) kömək üçün varam, yəni sənə kömək edə bilmərəm. Amma sən də özünə C Y B Σ R qura bilərsən. Kanala bax` @TheCyberUserBot'
                )
            else:
                await event.reply(
Exemplo n.º 7
0
from telethon.sync import TelegramClient
from telethon import functions, types
from telethon.tl.functions.channels import JoinChannelRequest
from telethon.tl.functions.channels import GetFullChannelRequest
from telethon.tl.functions.channels import InviteToChannelRequest
from telegram.ext.filters import Filters
import asyncio

api_id = 3409046
api_hash = '48ae9fbdf79edda291e1fa5796fc4665'
channel = '@pruebastienda'
#entity = client.get_entity(chn)
# Create the client and connect
client = TelegramClient(
    'sessionname', api_id,
    api_hash)  # feel free to edit %sessionname% as you want
client.connect()
print(client.get_me().stringify())

#async def main():
# await asyncio.wait(
# client(functions.channels.JoinChannelRequest(
# channel='jcolvera1991')))
Exemplo n.º 8
0
                ),
            )
        ]
    return pairs


with bot:
    try:
        tgbot = TelegramClient(
            "TG_BOT_TOKEN",
            api_id=API_KEY,
            api_hash=API_HASH).start(
            bot_token=BOT_TOKEN)

        dugmeler = CMD_HELP
        me = bot.get_me()
        uid = me.id

        @tgbot.on(events.NewMessage(pattern="/start"))
        async def handler(event):
            if event.message.peer_id.user_id != uid:
                await event.reply(
                    "I'm [ProjectAlf](https://github.com/alfianandaa/ProjectAlf) modules helper...\nplease make your own bot, don't use mine 😋"
                )
            else:
                await event.reply(f"`Hey there {ALIVE_NAME}\n\nI work for you :)`")

        @tgbot.on(events.InlineQuery)  # pylint:disable=E0602
        async def inline_handler(event):
            builder = event.builder
            result = None
Exemplo n.º 9
0
parser.add_argument('--api_key')
parser.add_argument('--session')
parser.add_argument('--from_channel', default=None)
parser.add_argument('--to_channel', default=None)
parser.add_argument('action', choices=['retrieve_channels', 'forward_posts'])
args = parser.parse_args()

print('Connecting to the Telegram...')
try:
    api_key = args.api_key.split(':')
    api_id = int(api_key[0])
    api_hash = api_key[1]
    session = args.session
    client = TelegramClient(session, api_id, api_hash)
    client.start()
    print('Logged in successfuly as @' + client.get_me().username)
except Exception as e:
    print("Couldn't connect to the Telegram:", e)
    exit(1)


def retrieve_channels():
    table = Texttable()
    table = table.header(['ID', 'Channel title', 'Username'])
    table = table.set_cols_width([12, 32, 33])
    table = table.set_cols_dtype(['t', 't', 't'])
    print('Retrieving dialogs...')
    for dialog in client.iter_dialogs():
        if dialog.is_channel:
            _id = str(dialog.entity.id)
            title = dialog.title
Exemplo n.º 10
0
                    level=logging.WARNING)


#LOAD API & BOT SECRETS
with open("/home/bot/voting_bot/discourse-voting-bot-telegram/telegram-secrets.json", 'r') as secrets_file:
    secret = json.load(secrets_file)

api_id = secret["id"]
api_hash = secret["hash"]
bot_token = secret["token"]

# We have to manually call "start" if we want an explicit bot token
bot = TelegramClient('bot', api_id, api_hash).start(bot_token=bot_token)

admins = bot.get_participants(chat, filter=ChannelParticipantsAdmins)
@bot.on(events.NewMessage(from_users=admins,pattern='/start'+'@'+bot.get_me().username))
async def start(event):
    """Send a message when the command /start is issued."""
    await event.respond('Hi!')
    raise events.StopPropagation

@bot.on(events.NewMessage(pattern='/help'+'@'+bot.get_me().username))
async def start(event):
    """Send a message when the command /help is issued."""
    await event.respond("The following commands are at your disposal: /start, /tip and /balance \n \n Initiating command /tip has a specfic format,\n use it like so:" + "\n \n Parameters: \n <user> = target user to tip \n <amount> = amount of votes to send \n \n Tipping format: \n /tip <user> <amount>")
    raise events.StopPropagation

@bot.on(events.NewMessage(pattern='/tip'+'@'+bot.get_me().username))
async def start(event):
    """Send a message when the command /tip is issued."""
    await event.respond("The following commands are at your disposal: /start, /tip and /balance \n \n Initiating command /tip has a specfic format,\n use it like so:" + "\n \n Parameters: \n <user> = target user to tip \n <amount> = amount of votes to send \n \n Tipping format: \n /tip <user> <amount>")
Exemplo n.º 11
0
from lxml import html
import socks , logging   , asyncio , random
import requests
from telethon import types as telethon_types
from telethon.tl import types as tl_telethon_types

### --- DEBUG 

logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',level=logging.INFO)
logger = logging.getLogger(__name__)

#--------- Starting Bot

bot = TelegramClient('when',1753946,'ba6b9d9fa75d4bbb6f09224e6cae8200')
bot.start()
info = bot.get_me()

#--------- Create Directories

for item in ['Database']:
    if not os.path.exists(item):
        os.mkdir(item)


#---------alert

print(f'Bot Connected on {info.username}  Successfully !')


#-------- Only Get  Online / Last Seen Recently Members.
Exemplo n.º 12
0
class TELEGRAM_CLIENT:
    def __init__(self, id: int, hash: str, session_name: str, phone_number: str, proxy = None):
        self.api_id = id
        self.api_hash = hash
        self.session_name = session_name
        self.phone_number = phone_number

        self.client = TelegramClient(self.session_name,
                                     self.api_id,
                                     self.api_hash,
                                     proxy = proxy)

        self.client.connect()

        if not self.client.is_user_authorized():
            try:
                self.client.send_code_request(self.phone_number)
                print('Code sent to ' + self.phone_number)
                self.code_sent = 1
            except:
                self.code_sent = 0

    def close_connection(self):
        try:
            self.client.disconnect()
            return {'response': 1}
        except:
            return {'response': False}

    def is_auth(self):
        if not self.client.is_user_authorized():
            return {'response': False}
        else:
            return {'response': 1}

    def enter_code(self, code, reg_data: list = ['Ivan', 'Ivanov']):
        try:
            self.me = self.client.sign_up(code=code,
                                          first_name=reg_data[0],
                                          last_name=reg_data[1])
            if not self.client.is_user_authorized():
                return {'response': False}
            else:
                return {'response': 1}
        except telethon.errors.rpcerrorlist.PhoneNumberOccupiedError:
            self.me = self.client.sign_in(self.phone_number, code)
            if not self.client.is_user_authorized():
                return {'response': False}
            else:
                return {'response': 1}

    def edit_2FA(self, new_password: str, current_password = None):
        try:
            if not current_password:
                self.client.edit_2fa(new_password=new_password)
            else:
                self.client.edit_2fa(current_password=current_password,
                                     new_password=new_password)
            return {'response': 1}
        except:
            return {'response': False}

    def clear_2FA(self, current_password: str):
        try:
            self.client.edit_2fa(current_password=current_password,
                                 new_password=None)
            return {'response': 1}
        except:
            return {'response': False}

    def get_me(self):
        try:
            client_me = self.client.get_me().stringify()
            return {'response': 1,
                    'client_me': client_me}
        except:
            return {'response': False, 'ban': 1}

    def change_username(self, username: str):
        try:
            result = self.client(functions.account.UpdateUsernameRequest(
                    username=username
                    ))
            return {'response': 1,
                    'result': result.stringify()}
        except:
            return {'response': False}
Exemplo n.º 13
0
class UI:
    def __init__(self):
        self.client = TelegramClient('token', api_id, api_hash)
        try:
            self.client.connect()
        except OSError:
            tk.messagebox.showerror('錯誤', '無法連線伺服器\n請檢查你的網路')

        if self.client.is_user_authorized():
            self.logged_in_windows = tk.Tk()
            self.logged_in_windows.title("快速刪除Telegram訊息({}已登入)".format(
                self.client.get_me().first_name))
            self.logged_in_windows.geometry('432x243')
            self.logged_in_windows.resizable(width=0, height=0)
            self.logged_in_windows.wm_attributes('-topmost', 1)
            self.chat_room = tk.Entry(self.logged_in_windows)
            self.chat_room.pack()
            tk.Label(
                self.logged_in_windows,
                text=
                '\n使用說明\n\n在上方輸入頻道、群組的share link或者私訊對方的username\n格式可以是 https://t.me/TGQNA @TGQNA 或者 TGQNA\n\n在下方選譯是僅刪除自己傳送的訊息還是刪除所有的訊息\n注意:刪除所有訊息時請確保你有對應的權限\n'
            ).pack()
            self.del_button = tk.Button(self.logged_in_windows,
                                        text='刪除自己的訊息',
                                        command=self.del_msg)
            self.del_button.pack()
            self.del_all_button = tk.Button(self.logged_in_windows,
                                            text='刪除全部的訊息',
                                            command=self.delall_msg)
            self.del_all_button.pack()
            self.logged_in_windows.mainloop()
        else:
            self.log_in_windows = tk.Tk()
            self.log_in_windows.title("快速刪除Telegram訊息(未登入)")
            self.log_in_windows.geometry('432x243')
            self.log_in_windows.resizable(width=0, height=0)
            self.log_in_windows.wm_attributes('-topmost', 1)
            tk.Label(master=self.log_in_windows,
                     text='國碼+電話號碼').place(x=20, y=50, height=26, width=100)
            tk.Label(master=self.log_in_windows, text='驗證碼').place(x=66,
                                                                   y=100,
                                                                   height=26,
                                                                   width=60)
            tk.Label(master=self.log_in_windows, text='密碼').place(x=72,
                                                                  y=150,
                                                                  height=26,
                                                                  width=60)
            self.phone_number = tk.Entry(master=self.log_in_windows)
            self.phone_number.place(x=144, y=50, height=26, width=220)
            self.code = tk.Entry(master=self.log_in_windows)
            self.code.place(x=144, y=100, height=26, width=100)
            self.password = tk.Entry(master=self.log_in_windows, show='*')
            self.password.place(x=144, y=150, height=26, width=220)
            self.get_code_button = tk.Button(master=self.log_in_windows,
                                             text='驗證碼',
                                             width=50,
                                             height=30,
                                             command=self.get_code)
            self.get_code_button.place(x=304, y=100, height=26, width=60)
            self.help_button = tk.Button(master=self.log_in_windows,
                                         text='說明',
                                         width=40,
                                         height=30,
                                         command=self.help)
            self.help_button.place(x=94, y=200, height=26, width=60)
            self.login_button = tk.Button(master=self.log_in_windows,
                                          text='登入',
                                          width=40,
                                          height=30,
                                          command=self.login)
            self.login_button.place(x=194, y=200, height=26, width=60)
            self.exit_button = tk.Button(master=self.log_in_windows,
                                         text='退出',
                                         width=40,
                                         height=30,
                                         command=self.exit)
            self.exit_button.place(x=294, y=200, height=26, width=60)
            self.log_in_windows.mainloop()

    def exit(self):
        self.log_in_windows.quit()

    def get_code(self):
        if len(self.phone_number.get()) <= 8:
            tk.messagebox.showerror(
                '錯誤', '請先輸入正確的電話號碼\n格式:國際電話區號+電話號碼\n例如:+85223802850')
            return
        try:
            self.sent = self.client.send_code_request(self.phone_number.get())
            self.hash = self.sent.phone_code_hash
        except:
            tk.messagebox.showerror('未知錯誤', '無法取得驗證碼,請兩分鐘後再試!')

    def help(self):
        tk.messagebox.showinfo(
            '使用說明',
            '電話號碼格式國際電話區號+電話號碼\n例如:+85223802850\n\n驗證碼是5位數字的\n密碼是雙步驟驗證(2FA)密碼,沒有就留空'
        )

    def del_msg(self):
        self.me = self.client.get_me()
        for self.message in self.client.iter_messages(self.chat_room.get()):
            if self.message.from_id == self.me.id:
                self.client.delete_messages(self.chat_room.get(),
                                            self.message.id)
                print(self.message.id)
        tk.messagebox.showinfo('成功',
                               '成功刪除 {} 裡自己傳送的訊息'.format(self.chat_room.get()))

    def delall_msg(self):
        for self.message in self.client.iter_messages(self.chat_room.get()):
            self.client.delete_messages(self.chat_room.get(), self.message.id)
            print(self.message.id)
        tk.messagebox.showinfo('成功',
                               '成功刪除 {} 裡所有的訊息'.format(self.chat_room.get()))

    def login(self):
        if len(self.code.get()) != 5:
            tk.messagebox.showerror('錯誤', '請先輸入正確的驗證碼')
            return
        try:
            self.client.sign_in(phone=self.phone_number.get(),
                                code=self.code.get(),
                                password=self.password.get(),
                                phone_code_hash=self.hash)
        except:
            tk.messagebox.showerror('未知錯誤', '無法登入!')
            return
        tk.messagebox.showinfo('登入成功', '請重新啟動這個應用程式!')
        self.log_in_windows.quit()
Exemplo n.º 14
0
                          custom.Button.inline(
                              "»»", data=f"{prefix}_next({modulo_page})"),
                      )]

    return pairs


with bot:
    try:
        from userbot.modules.button import BTN_URL_REGEX, build_keyboard
        from userbot.modules.sql_helper.bot_blacklists import check_is_black_list
        from userbot.modules.sql_helper.bot_pms_sql import add_user_to_db, get_user_id
        from userbot.utils import reply_id

        dugmeler = CMD_HELP
        user = bot.get_me()
        uid = user.id
        owner = user.first_name
        logo = ALIVE_LOGO
        logoman = INLINE_PIC
        tgbotusername = BOT_USERNAME

        @tgbot.on(events.NewMessage(incoming=True,
                                    func=lambda e: e.is_private))
        async def bot_pms(event):
            chat = await event.get_chat()
            if check_is_black_list(chat.id):
                return
            if chat.id != uid:
                msg = await event.forward_to(uid)
                try:
Exemplo n.º 15
0
                )
            )
        ]
    return pairs


with bot:
    try:
        tgbot = TelegramClient(
            "TG_BOT_TOKEN",
            api_id=API_KEY,
            api_hash=API_HASH).start(
            bot_token=BOT_TOKEN)

        dugmeler = CMD_HELP
        me = bot.get_me()
        uid = me.id

        @tgbot.on(events.NewMessage(pattern="/start"))
        async def handler(event):
            if event.message.from_id != uid:
                await event.reply("I'm [NFALBOT](https://github.com/meareyou/NfalBot) modules helper...\nplease make your own bot, don't use mine 😋")
            else:
                await event.reply(f"`Hey there {ALIVE_NAME}\n\nI work for you :)`")

        @tgbot.on(events.InlineQuery)  # pylint:disable=E0602
        async def inline_handler(event):
            builder = event.builder
            result = None
            query = event.text
            if event.query.user_id == uid and query.startswith("@UserButt"):
Exemplo n.º 16
0
group = bot_client.loop.run_until_complete(groupGetter(groupLink, bot_client))
catch = bot_client.loop.run_until_complete(catcher(group, bot_client))
fetch_group = FetchGroup.objects(group_id=group.id).first()
answer_index = fetch_group["index_remain"]

for SES in sessionString:
    print("--------------------")

    bot_client.disconnect()
    string = sessionString[n]["session"]
    bot_client = TelegramClient(StringSession(string), api_id, api_hash)
    bot_client.connect()
    bot_client.loop.run_until_complete(joinner(groupLink, bot_client))

    me = bot_client.get_me()
    print(f"{me.username}  is starting")
    catch = catch[answer_index:]
    answer = whistle(bot_client, catch)
    answer_index = answer["Added"] + answer_index
    n += 1
    me = bot_client.get_me()
    cooldown = answer["cooldown"]

    if not fetch_group:
        fetch_group = FetchGroup(group_id=group.id,
                                 group_link=groupLink,
                                 index_remain=answer_index)
        fetch_group.save()

    fetch_group.index_remain = answer_index
Exemplo n.º 17
0
        'size': 300,
        'mime_type': 'image/jpeg',
        'attributes': DocumentAttributeImageSize(48, 48)
    }
}

COMMON_THUMB_CONFIG = _THUMB_CONFIG['common']

# === Logging and bot settings ================================================

# Set logging
logformat = '[%(levelname) 5s/%(asctime)s] %(name)s: %(message)s'
logging.basicConfig(format=logformat, level=logging.WARNING)

# Set bot configurations: session name, api_id and api_hash
session_name = 'translator-bot' if not TEST_MODE else 'translator-bot-test'
api_id = eval(get('API_ID'))
api_hash = get('API_HASH')

# Prevent the situation when another client was already connected.
# **Caution**: Doing this action ends the previous client session.
disconnect()

# Connect to Telegram
bot = TelegramClient(session_name, api_id, api_hash).start(bot_token=TOKEN)

# Now it is connected, get some data
bot_data = bot.get_me()
BOT_ID: int = bot_data.id
BOT_USERNAME: str = bot_data.username
Exemplo n.º 18
0
from telethon.sync import TelegramClient
client = TelegramClient('telethon', api_id='', api_hash='')
client.start()

if input(
        'Are you sure you want to delete your *every outgoing message* in *every group*? (y/N): '
) != 'y':
    exit(0)

message_ids = []
counter = 0

for dialog in client.get_dialogs():
    if dialog.is_group:
        for message in client.iter_messages(dialog.entity,
                                            from_user=client.get_me()):
            message_ids.append(message.id)
            counter += 1
            print('Message ID: %d, Chat ID: %d, Chat Title: %s' %
                  (message.id, dialog.id, dialog.title))
            if len(message_ids) > 99:
                client.delete_messages(client.get_entity(dialog.entity),
                                       message_ids)
                print('%d messages were deleted.' % len(message_ids))
                message_ids = []
        client.delete_messages(client.get_entity(dialog.entity), message_ids)

print('Total %d messages were deleted.' % counter)
print(
    'Done! (Please run the script two to three times to clean every message. If you run once only, some messages may won\'t be deleted.)'
)