Exemple #1
0
def start(update: Update, context: CallbackContext) -> None:
    """Start bot"""
    global count
    
    count = 1
    reply_keyboard = [['/start'],['/queue'],['/help']]

    """Send a deep-linked URL when the command /start is issued."""
    bot = context.bot
    
    url = helpers.create_deep_linked_url(
        bot.get_me().username,
        DECR8,
        group=True
        )
    
    text = ("👺" "{} items found".format(len(d)))
    
    update.message.reply_text(
        text,
        reply_markup=ReplyKeyboardMarkup(
            reply_keyboard,
            parse_mode=ParseMode.MARKDOWN,
            one_time_keyboard=True
        )
    )
    
    return STAGE1
def deep_linked_level_2(update, context):
    """Reached through the SO_COOL payload"""
    bot = context.bot
    url = helpers.create_deep_linked_url(bot.get_me().username, USING_ENTITIES)
    text = "You can also mask the deep-linked URLs as links: " \
           "[▶️ CLICK HERE]({}).".format(url)
    update.message.reply_text(text, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True)
Exemple #3
0
def registertoken_handler(update, context):

    chat_id = update.effective_chat.id
    chat_name = update.effective_chat.title
    #create deeplink
    url = helpers.create_deep_linked_url(context.bot.get_me().username)
    #create button with deeplink to bot
    buttonmarkup = InlineKeyboardMarkup.from_button(InlineKeyboardButton(text="Start chat", url=url))

    #check if its group/private chat
    if update.effective_chat.type != 'private':
        print('grup')
        msg = open_message("user","regtokengroup")
        #update.message.reply_text(text="Sorry, register token not supported for group type.\nPlease invoke this cmd inside private chat, click button below", reply_markup=buttonmarkup)
        update.message.reply_text(text=msg, reply_markup=buttonmarkup)
        return ConversationHandler.END
    
    else:
        db = dbhelper.Database()
        db.connection()
        if db.getOwner(chat_id=chat_id):
            msg = open_message("owner","regtoken")
            #update.message.reply_text(text=f"You have already imported your token.\n\nIf you want to change it, please unregister first then register it again", parse_mode=ParseMode.HTML)
            update.message.reply_text(text=msg, parse_mode=ParseMode.HTML)
            return ConversationHandler.END
        else:
            msg = open_message("user","regtoken")
            #update.message.reply_text(text=f"Hi, Please send me your <b>.sdtid</b> file\n\nor url token that look like this \n<code>http://127.0.0.1/securidxxxxx</code>\n\n Click /cancel to cancel", parse_mode=ParseMode.HTML)
            update.message.reply_text(text=msg, parse_mode=ParseMode.HTML)
            return TOKEN
def psychologists_room(update, context):
    user = update.effective_user
    assign_url = helpers.create_deep_linked_url(context.bot.get_me().username,
                                                "psychologist_" + str(user.id))
    conversations.request_conversation(user_id=user.id,
                                       first_name=user.first_name,
                                       last_name=user.last_name,
                                       username=user.username,
                                       type=ConversationType.SOCIAL)
    context.bot.send_message(chat_id=settings.TELEGRAM_PSYCHOLOGIST_ROOM,
                             text=f"A user wants to talk!\n\n"
                             f"Name: {user.first_name}\n"
                             f"Username: @{user.username}\n"
                             f"Case description: {update.message.text}",
                             disable_web_page_preview=True,
                             reply_markup=InlineKeyboardMarkup([[
                                 InlineKeyboardButton("Assign Case to me",
                                                      url=assign_url),
                                 InlineKeyboardButton(callback_data="report_" +
                                                      str(user.id),
                                                      text="Report User")
                             ]]))
    update.message.reply_text(
        "Forwarded your request to the psychologists' room!",
        reply_markup=ReplyKeyboardRemove(),
    )
    return ConversationHandler.END
Exemple #5
0
def start(update, context):
    """Sends humiliating message to chats"""
    global BOT

    BOT = context.bot
    chat_id = update.message.chat_id
    print("BOT: ", BOT)
    userId = update.message.from_user['username']
    if userId not in user_groups:
        print("Initiating new user")
        user_groups[userId] = []
    user_groups[userId].append(chat_id)
    print("USER GROUPS: ", user_groups)

    url = helpers.create_deep_linked_url(BOT.get_me().username,
                                         CHECK_THIS_OUT,
                                         group=True)

    update.message.reply_text(
        f'Howdy Good day {update.effective_chat.first_name}')
    if chat_id > 0:
        text = f"Add this to people you care about \n {url}"
        update.message.reply_text(text)
    else:
        text = f"Your group id is: \n`{chat_id}`\n(You can tap this to copy to clipboard!)\nAdd this to Shake Master!"
        update.message.reply_markdown(text)
Exemple #6
0
def deep_linked_level_2(update: Update, context: CallbackContext) -> None:
    """Reached through the SO_COOL payload"""
    bot = context.bot
    url = helpers.create_deep_linked_url(bot.username, USING_ENTITIES)
    text = f"You can also mask the deep-linked URLs as links: [▶️ CLICK HERE]({url})."
    update.message.reply_text(text,
                              parse_mode=ParseMode.MARKDOWN,
                              disable_web_page_preview=True)
Exemple #7
0
def start(update, context):
    """Send a deep-linked URL when the command /start is issued."""
    bot = context.bot
    url = helpers.create_deep_linked_url(bot.get_me().username,
                                         CHECK_THIS_OUT,
                                         group=True)
    text = "Feel free to tell your friends about it:\n\n" + url
    update.message.reply_text(text)
def open_bot(update, context):
    x = update.message.from_user.id
    print(x)
    bot = context.bot
    url = helpers.create_deep_linked_url(bot.get_me().username, SO_COOL)
    keyboard = InlineKeyboardMarkup.from_button(
        InlineKeyboardButton(text='Get Resource here!', url=url))
    #context.bot.sendMessage(chat_id=update.message.chat.id,text ="        Hello",reply_markup=keyboard)
    update.message.reply_text("Hello", reply_markup=keyboard)
Exemple #9
0
def add_to(update, context):
    bot = context.bot
    url = helpers.create_deep_linked_url(bot.get_me().username,
                                         "unique token here",
                                         group=True)
    return InlineKeyboardMarkup([[
        InlineKeyboardButton(text="only for me", callback_data="me"),
        InlineKeyboardButton(text="add to telegram group", url=url),
    ]])
Exemple #10
0
def deep_linked_level_1(update, context):
    """Reached through the CHECK_THIS_OUT payload"""
    bot = context.bot
    url = helpers.create_deep_linked_url(bot.get_me().username, SO_COOL)
    text = "Awesome, you just accessed hidden functionality! " \
           " Now let's get back to the private chat."
    keyboard = InlineKeyboardMarkup.from_button(
        InlineKeyboardButton(text='Continue here!', url=url))
    update.message.reply_text(text, reply_markup=keyboard)
Exemple #11
0
def activity_command(update, context):
    chat = update.effective_message.chat
    user = update.effective_message.from_user
    message = update.effective_message
    data = message.text.split(' ')
    day = 7
    if len(data) > 1 and data[1].isdigit():
        day = int(data[1])
        if day > 42:
            update.message.reply_text('داده ها حداکثر 42 روز نگهداری میشوند')
            return

    data = get_admins_data(chat.id, day)
    if user.id not in data and user.id not in bot_admins():
        update.message.reply_text('آمار مدیران فقط برای مدیران قابل مشاهده است زاخا')
        return

    if update.effective_message.reply_to_message:
        target_user = update.effective_message.reply_to_message.from_user.id
        target_chat = chat.id
        msg = get_user_data(target_user, target_chat, day, user)
        try:
            bot.send_message(user.id, msg, 'HTML', disable_web_page_preview=True)
            update.message.reply_text('آمارشو پی وی گذاشتم')
            return
        except Exception as e:
            print(e)
            update.message.reply_text('اول مطمئن شو که استارت کردی منو ')
            return

    header = """◗آمار ادمین ها توی {days} روز گذشته در گروه {group} 📊V6.1

🎮 تعداد بازی ها
🔔 تعداد تگ ها
😴 تعداد AFK ها
💬 تعداد پیام ها
@username  |🎮|🔔|😴|💬

""".format(days=day, group=bot.get_chat(chat.id).title)
    args = ['{}  | {} | {} | {} | {} | <a href="{}">Detail</a>'.format(
        mention_html(i, data[i]['username'] if data[i]['username'] else str(i)),
        data[i]['game'],
        data[i]['tag'],
        data[i]['afk'],
        data[i]['msg'],
        create_deep_linked_url(bot.username, 'adminStats_{}_{}_{}'.format(i, chat.id, day))
        # 'https://t.me/manage_ww_bot?start=adminStats_{}_{}'.format(i, chat.id)
    ) for i in data]
    try:
        bot.send_message(user.id, header + '\n'.join(args), 'HTML', disable_web_page_preview=True)
        update.message.reply_text('پی وی چک')
    except Exception as e:
        print(e)
        update.message.reply_text('اول مطمئن شو که استارت کردی منو ')
Exemple #12
0
def get_book(book: str, i=0) -> str:
    url = create_deep_linked_url(BOT_USERNAME, f"READ-{book}")
    end = ending(book, i)
    res = lookup(end)
    if res == url:
        return DOMAIN + end
    res = shorten(url, end)
    if res:
        return res
    if i > 4:
        return url
    return get_book(book, i + 1)
Exemple #13
0
 def __post_init__(self):
     try:
         self.modul = self.modul if self.modul else self.title.split(
             "-")[0].strip()
     except Exception:
         self.modul = ""
     self.rbv_url = (
         self.rbv_url if self.rbv_url else
         f"http://www.pustaka.ut.ac.id/reader/index.php?modul={self.modul}"
         if self.modul else None)
     self.bookimages_url = (
         self.bookimages_url if self.bookimages_url else
         f"http://bahanajar.ut.ac.id/bookimages/{self.id}.jpg")
     self.bookdetail_url = (
         self.bookdetail_url if self.bookdetail_url else
         f"http://bahanajar.ut.ac.id/books/bookdetail/{self.id}")
     try:
         kode = Modul.validate(self.modul)
         self.depp_link_url = create_deep_linked_url(
             BOT_USERNAME, f"READ-{kode}")
     except Exception:
         self.depp_link_url = create_deep_linked_url(BOT_USERNAME, "READ")
Exemple #14
0
def sibyl_ban_alert(update: Update, context: CallbackContext) -> Optional[str]:
    message = update.effective_message
    chat = update.effective_chat
    users = update.effective_message.new_chat_members
    bot = context.bot
    if not users:
        return

    if not does_chat_sibylban(chat.id):
        return

    if sibylClient:
        log_stat, act = get_sibyl_setting(chat.id)
        if act != 3:  # just for alert mode
            return

        for user in users:
            try:
                data = sibylClient.get_info(user.id)
            except GeneralException:
                return
            except BaseException as e:
                logging.error(e)
                return

            if data.banned:
                txt = '''{} has a <a href="https://t.me/SibylSystem/3">Crime Coefficient</a> of {}\n'''.format(
                    user.mention_html(),
                    data.crime_coefficient,
                )
                txt += "<b>Enforcement Mode:</b> None"
                url = helpers.create_deep_linked_url(
                    bot.username, f"sibyl_banned-{user.id}")

                keyboard = [[InlineKeyboardButton(text="More Info", url=url)]]

                reply_markup = InlineKeyboardMarkup(keyboard)
                log_msg = "#SIBYL_BAN #{}".format(", #".join(
                    data.ban_flags)) if data.ban_flags else "#SIBYL_BAN"
                log_msg += f"\n • <b>User:</b> {user.mention_html()}\n"
                log_msg += f" • <b>Reason:</b> <code>{data.reason}</code>\n" if data.reason else ""
                log_msg += f" • <b>Ban time:</b> <code>{data.date}</code>\n" if data.date else ""
                log_msg += " • <b>Enforcement Mode:</b> None"
                message.reply_html(text=txt,
                                   disable_web_page_preview=True,
                                   reply_markup=reply_markup)

                if log_stat:
                    return log_msg

                handle_sibyl_banned(user, data)
Exemple #15
0
def share_link(update: Update, context: CallbackContext) -> int:
    query = update.callback_query
    query.answer()
    bot = context.bot

    user_data = context.user_data['payment']
    numOfPersons = int(user_data['Number of people'])

    payloads = []
    i = 0
    if (context.user_data['payment']['equal']['bool'] == True):
        text = f"{facts_to_str(user_data)}"
    else:
        text = f"{multi_users_to_str(user_data)}"

    event_id = add_event(context.user_data['user_id'], user_data['Title'])
    while i < numOfPersons:
        payloads.append(generate_token())
        # TODO: link can only share to groups not individuals
        url = helpers.create_deep_linked_url(bot.username, str(payloads[i]))
        if (context.user_data['payment']['equal']['bool'] == True):
            amount = int(context.user_data['payment']['Amount'])
            add_payment(context.user_data['user_id'], amount / numOfPersons,
                        event_id, str(payloads[i]), user_data['Title'])
            text += (
                f"Share the payment information to your friend {i+1}: [▶️ CLICK HERE]({url}). \n"
            )
        else:
            amount = context.user_data['payment']['Amount'][i + 1]['amount']
            add_payment(context.user_data['user_id'], amount, event_id,
                        str(payloads[i]), user_data['Title'])
            text += (
                f"Share the payment information to *{context.user_data['payment']['Amount'][i+1]['name']}* : [▶️ CLICK HERE]({url}). \n"
            )
        i += 1

    keyboard = [[InlineKeyboardButton(BACK, callback_data=str("start"))]]
    reply_markup = InlineKeyboardMarkup(keyboard)

    # clear payment
    context.user_data['payment'] = {}
    # create_deep_linked_url(bot_username, payload=None, group=False)
    # the link will start the bot with /start, cant start with other command
    # url = helpers.create_deep_linked_url(bot.username, CHECK_THIS_OUT, group=True)
    query.edit_message_text(text=text,
                            parse_mode='Markdown',
                            disable_web_page_preview=True,
                            reply_markup=reply_markup)

    return START_OVER
Exemple #16
0
def generate(update: Update, context: CallbackContext):
    """
    method to create a deep link and send it to the current user for sharing
    """

    # generating a sharable link with the payload
    # documentation: https://python-telegram-bot.readthedocs.io/en/stable/telegram.utils.helpers.html#telegram.utils.helpers.create_deep_linked_url
    url = create_deep_linked_url(context.bot.get_me().username,
                                 update.message.chat.username)
    update.message.reply_text(
        text=
        "Share it with your friends: %s.\n Copy the link and share it with them"
        % url)
    pass
Exemple #17
0
def deep_linked_level_2(update: Update, context: CallbackContext) -> None:
    """Reached through the SO_COOL payload"""
    bot = context.bot
    
    url = helpers.create_deep_linked_url(
        bot.get_me().username,
        USING_ENTITIES
    )

    text = " ""[▶️ STOP BOT]({}).".format(url)
    update.message.reply_text(
        text,
        parse_mode=ParseMode.MARKDOWN,
        disable_web_page_preview=True
    )
Exemple #18
0
def to_referral_tender(update, context):
    user_id = update.callback_query.from_user.id
    query = update.callback_query
    language = context.user_data['user'].get('language')
    invited_users = referral.get_invited_users(
        user_id, context.user_data['referral_tender'].get('id'))
    link = helpers.create_deep_linked_url(context.bot.get_me().username,
                                          str(user_id))
    referral_message = strings.from_referral_tender(
        context.user_data['referral_tender'], language, len(invited_users),
        link)
    referral_keyboard = keyboards.get_keyboard('referral', language)
    query.edit_message_caption(caption=referral_message,
                               reply_markup=referral_keyboard,
                               parse_mode=ParseMode.HTML)
    return ConversationHandler.END
Exemple #19
0
def messageSender():
    alljobs = json.load(
        open('/home/anonny/scrapers/coders_needed/data.json'))
    for data in alljobs:
        message = """\nJob Title: {}\n\nCompany: {}\n\nJob Type: {}\n\nDescription: {}""".format(
            data['title'], data['company'], data['jobtype'], data['desc']
        )

        deepURL = helpers.create_deep_linked_url(
            bot.get_me().username, data['job_id'], group=False)
        keyboard = [[InlineKeyboardButton(
            "Apply", callback_data='some_message', url=deepURL),
            InlineKeyboardButton(
            "Share", callback_data='share_applicatoin'), ]]

        x = bot.send_message(chat_id=BOT_ID, text=message,
                             reply_markup=InlineKeyboardMarkup(keyboard))
Exemple #20
0
def check_space(update, context):
    space_handles = context.user_data["space_handles"]
    chosen_handle = update.message.text
    if "/" in chosen_handle:
        chosen_handle = update.message.text[1:]
    if chosen_handle in space_handles:
        qr_payload = create_deep_linked_url(os.environ["USER_BOT_NAME"],
                                            chosen_handle)
        qr_request_url = "http://qr:8080/?data={}".format(qr_payload)
        r = requests.get(qr_request_url)
        if r.status_code == 200:
            photo = io.BytesIO(r.content)
            context.bot.send_photo(chat_id=update.effective_chat.id,
                                   photo=io.BufferedReader(photo))
        return ConversationHandler.END
    else:
        context.bot.send_message(chat_id=update.effective_chat.id,
                                 text="Incorrect handle")
        return generateqr(update, context)
Exemple #21
0
def buttonPressedNotify(update, context):
    name = update.callback_query.from_user.first_name
    username = update.callback_query.from_user.username
    chat_title = update.callback_query.message.chat.title
    
    if update.effective_chat.type != 'private':
        msg = open_message("alluser","notifyadmingroup")
        url = helpers.create_deep_linked_url(context.bot.get_me().username)
        buttonmarkup = InlineKeyboardMarkup.from_button(InlineKeyboardButton(text="Start chat", url=url))
        
        context.bot.send_message(chat_id=166942761 ,text=f'Manggil bos\nGroup: {chat_title}\nFrom: {name} @{username}.')
        update.callback_query.edit_message_reply_markup(reply_markup=None)
        #update.callback_query.message.reply_text(text="Admin has been notified, please wait.\n\nPlease issue /start on the button below to initiate conversation with admin.\nIf you have done this before, it's not necessary.", reply_markup=buttonmarkup)
        update.callback_query.message.reply_text(text=msg, reply_markup=buttonmarkup)
    else:
        msg = open_message("alluser","notifyadmin")
        context.bot.send_message(chat_id=166942761 ,text=f'Manggil bos\nGroup: {chat_title}\nFrom: {name} @{username}.')
        update.callback_query.edit_message_reply_markup(reply_markup=None)
        #update.callback_query.message.reply_text(text="Admin has been notified, please wait.")
        update.callback_query.message.reply_text(text=msg)
Exemple #22
0
def deep_linked_level_1(update: Update, context: CallbackContext) -> None:
    """Reached through the CHECK_THIS_OUT payload"""
    bot = context.bot
    try:
        result_id = [
            v
            for k, v in d.items()
        ]
        track_url = "https://t.me/crateofnotsodasbutmusic/{}".format(
            random.choice(result_id)
        )
        for i in range(1):
            update.message.reply_text(
                "::*decr8* ""[🎧]({})".format(track_url),
                parse_mode=ParseMode.MARKDOWN
            )
    except (BadRequest) as e:
        logger.warning(e)                                                      

    url = helpers.create_deep_linked_url(
        bot.get_me().username,
        SO_COOL
    )
    
    text = (
        "let's go to the private chat for more.\ni will not spam here."
    )
    
    keyboard = InlineKeyboardMarkup.from_button(
        InlineKeyboardButton(
            text='go to bot chat',
            url=url
        )
    )
    
    update.message.reply_text(
        text,
        reply_markup=keyboard
    )
def doctors_room(update, context):
    user = update.effective_user
    assign_url = helpers.create_deep_linked_url(context.bot.get_me().username,
                                                "doctor_" + str(user.id))
    conversations.new_user(user.id)
    context.bot.send_message(chat_id=settings.TELEGRAM_DOCTOR_ROOM,
                             text=f"A user requested medical help!\n\n"
                             f"Name: {user.first_name}\n"
                             f"Username: @{user.username}\n"
                             f"Case description: {update.message.text}",
                             disable_web_page_preview=True,
                             reply_markup=InlineKeyboardMarkup([[
                                 InlineKeyboardButton("Assign Case to me",
                                                      url=assign_url),
                                 InlineKeyboardButton(callback_data="report_" +
                                                      str(user.id),
                                                      text="Report User")
                             ]]))
    update.message.reply_text(
        "Forwarded your request to the doctor's room!",
        reply_markup=ReplyKeyboardRemove(),
    )
    return ConversationHandler.END
def newmember(update, context):
    """Send a message when the command /help is issued."""
    query = update.callback_query
    bot = context.bot
    url = helpers.create_deep_linked_url(bot.get_me().username, SO_COOL)
    text = "歡迎來到IT谷"
    keyboard = InlineKeyboardMarkup.from_button(
        InlineKeyboardButton(text='Continue here!', url=url))
    ogg_url = 'https://github.com/timothylam1228/CodeDeployGitHubDemo/raw/master/source/plato.ogg'
    for member in update.message.new_chat_members:
        update.message.reply_text(text, reply_markup=keyboard)
        context.bot.send_voice(chat_id=update.message.chat.id, voice=ogg_url)
        new_members = update.message.new_chat_members
        firstname = member.first_name
        lastname = member.last_name
        if ("+852" in firstname):
            bot.kick_chat_member(chat_id=update.message.chat.id,
                                 user_id=update.message.from_user.id)
            return
        elif ("+852" in lastname):
            bot.kick_chat_member(chat_id=update.message.chat.id,
                                 user_id=update.message.from_user.id)
            return
def vagas(update, context):
    bot = context.bot
    url = helpers.create_deep_linked_url(bot.username, SO_COOL)

    keyboard = InlineKeyboardMarkup.from_button(
        InlineKeyboardButton("Só me chame se nunca falou comigo rs", url=url))

    context.bot.send_message(
        chat_id=update.effective_chat.id,
        text="Humano para receber vagas me chame no privado.",
        reply_markup=keyboard)

    context.bot.send_message(
        chat_id=update.effective_user.id,
        text="Vagas de Visão Computacional \n\n" +
        "Visão Computacional -> https://www.linkedin.com/jobs/search/?geoId=106057199&keywords=%22Vis%C3%A3o%20computacional%22%20%22OpenCV%22&location=Brasil"
        +
        "A Até conseguirmos criar uma plataforma de visualização dessas vagas aqui no grupo, iremos usar o link acima.\n\n "
        +
        "Se eu apresentar mal funcionamento, fale com os idiotas que cuidam da minha manutenção:\n"
        + "@ natalia_py, @andreemidio1 , @ TioPerneta e @ hugueds \n\n" +
        "Parem de vacilação e corram atrás, se você não for, você é um bundão !! \n\n"
    )
Exemple #26
0
def initiate(update: Update, context: CallbackContext) -> int:  # Entry_point
    """This function is called when user uses /tell. It branches into 3- 'birthday', 'nickname' and 'nothing'."""

    chat = update.effective_chat
    first_name = update.effective_user.first_name

    if chat.type != "private":
        link = create_deep_linked_url(bot_username=context.bot.username,
                                      payload="tell")
        tell_markup = InlineKeyboardMarkup(
            [[InlineKeyboardButton(text="Let's go like you say!", url=link)]])

        context.bot.send_message(
            chat_id=chat.id,
            text="Just come to another chat I want to talk to you like you say",
            reply_markup=tell_markup)

        logger(
            message=f"{first_name} just tried using /tell in a {chat.type}. "
            f"A message telling them to use it in private was sent.")

        del chat, first_name, link, tell_markup
        return -1

    name = get_nick(update, context)

    context.bot.send_message(
        chat_id=chat.id,
        text=
        f'What do you want to tell me {name}? Type /cancel anytime to switch me off',
        reply_to_message_id=update.message.message_id,
        reply_markup=markup)

    logger(message=f"/tell", update=update, command=True)

    del name
    return CHOICE
Exemple #27
0
import logging.config
import re
from functools import wraps

from telegram import Update, TelegramError, Chat, ParseMode, Bot, BotCommandScopeAllPrivateChats, BotCommand
from telegram.error import BadRequest
from telegram.ext import Updater, CommandHandler, CallbackContext, Filters, MessageHandler
from telegram.utils import helpers

from mwt import MWT
from config import config

updater = Updater(config.telegram.token, workers=0)


DEEPLINK_SUPERGROUPS_EXPLANATION = helpers.create_deep_linked_url(updater.bot.username, "supergroups")

SUPERGROUPS = """I see you're wondering why I left your chat, uh? Well it's not easy to explain, but I'll try my best.

I'm a bot that was built to let people leave groups without loosing the messages history.
When you leave a Telegram group (or when you are removed by an admin), you will loose access to the messages history \
in that chat. Luckily, bots can remove users by asking Telegram to kick them out of groups without wiping out the \
messages history, so they will still be able to access it even after they are removed. Pretty coool uh?
The sad part is that this works in "normal" groups only - that is, group chats that haven't been converted to \
supergroup yet.

<i>"What? My group is not a supergroup, I don't even know what a supergroup is"</i>, you might be thinking. \
Here comes the complicated part, but bear with me. In Telegram, there are two types of groups: the so-called \
"normal groups" (or "legacy groups"), and supergroups. When you create a Telegram group, you always create a \
<i>normal</i> group. Normal groups offer a limited set of features: when you use one of the features that are not \
supported by normal groups, the group is automatically upgraded to supergroup. This all happens silently \
    def test_create_deep_linked_url(self):
        username = '******'

        payload = "hello"
        expected = f"https://t.me/{username}?start={payload}"
        actual = helpers.create_deep_linked_url(username, payload)
        assert expected == actual

        expected = f"https://t.me/{username}?startgroup={payload}"
        actual = helpers.create_deep_linked_url(username, payload, group=True)
        assert expected == actual

        payload = ""
        expected = f"https://t.me/{username}"
        assert expected == helpers.create_deep_linked_url(username)
        assert expected == helpers.create_deep_linked_url(username, payload)
        payload = None
        assert expected == helpers.create_deep_linked_url(username, payload)

        with pytest.raises(ValueError):
            helpers.create_deep_linked_url(username, 'text with spaces')

        with pytest.raises(ValueError):
            helpers.create_deep_linked_url(username, '0' * 65)

        with pytest.raises(ValueError):
            helpers.create_deep_linked_url(None, None)
        with pytest.raises(ValueError):  # too short username (4 is minimum)
            helpers.create_deep_linked_url("abc", None)
Exemple #29
0
def check_channel(update, context):
    def no_user_in_channel():
        if update.message:
            channel = context.bot.get_chat(
                chat_id=Config.TELEGRAM_CHANNEL_USERNAME)
            channel_message = strings.get_string(
                'referral.channel', language).format(channelName=channel.title)
            channel_keyboard = keyboards.get_channel_keyboard(
                Config.TELEGRAM_CHANNEL_LINK, language)
            update.message.reply_text(text=channel_message,
                                      reply_markup=channel_keyboard,
                                      parse_mode=ParseMode.HTML)
        else:
            error_message = strings.get_string('referral.channel.empty',
                                               language)
            update.callback_query.answer(text=error_message, show_alert=True)

    user_id = update.effective_user.id
    language = context.user_data['user'].get('language')
    try:
        user = context.bot.get_chat_member(
            chat_id=Config.TELEGRAM_CHANNEL_USERNAME, user_id=user_id)
        if user.status == 'left':
            no_user_in_channel()
            return
    except BadRequest as error:
        if error.message == 'User not found':
            no_user_in_channel()
        else:
            raise error
    else:
        referral_tender = referral.get_current_referral_tender()
        if not referral_tender:
            not_exist_message = strings.get_string('referral.not_exist',
                                                   language)
            if update.message:
                update.message.reply_text(text=not_exist_message)
            else:
                update.callback_query.answer(text=not_exist_message,
                                             show_alert=True)
                context.bot.delete_message(
                    chat_id=update.callback_query.message.chat.id,
                    message_id=update.callback_query.message.message_id)
            latest_referral_tender = referral.get_latest_tender()
            if not latest_referral_tender:
                return
            latest_referral_tender_info = strings.from_latest_referral_tender(
                latest_referral_tender, language)
            context.bot.send_message(chat_id=user_id,
                                     text=latest_referral_tender_info,
                                     parse_mode=ParseMode.HTML)
            return
        context.user_data['referral_tender'] = referral_tender
        invited_users = referral.get_invited_users(user_id,
                                                   referral_tender.get('id'))
        link = helpers.create_deep_linked_url(context.bot.get_me().username,
                                              str(user_id))
        referral_message = strings.from_referral_tender(
            referral_tender, language, len(invited_users), link)
        referral_keyboard = keyboards.get_keyboard('referral', language)
        image = images.get_referral_image(language)
        if update.callback_query:
            context.bot.delete_message(
                chat_id=user_id,
                message_id=update.callback_query.message.message_id)
        if image:
            message = context.bot.send_photo(chat_id=user_id,
                                             photo=image,
                                             caption=referral_message,
                                             reply_markup=referral_keyboard,
                                             parse_mode=ParseMode.HTML)
        else:
            if update.message:
                message = update.message.reply_text(
                    text=referral_message,
                    reply_markup=referral_keyboard,
                    parse_mode=ParseMode.HTML)
            else:
                message = update.callback_query.edit_message_text(
                    text=referral_message,
                    reply_markup=referral_keyboard,
                    parse_mode=ParseMode.HTML)
        if 'referral_message_id' in context.user_data:
            try:
                context.bot.delete_message(
                    chat_id=user_id,
                    message_id=context.user_data['referral_message_id'])
            except BadRequest:
                pass
        context.user_data['referral_message_id'] = message.message_id
def prepare_pin_message_kbd(bot_: bot, destination: str):
    url = helpers.create_deep_linked_url(bot_username=bot_.get_me().username,
                                         payload=destination)
    return make_single_button_kbd('start', url)