예제 #1
0
파일: Sendinga.py 프로젝트: aerosadegh/rss
    async def on_chat_message(self, msg):
        global RSSFLink, fk, Feeds
        await self._cancel_last()
        if msg['text'] == 'more':
            ff = Feeds[fk[0]][fk[1]:fk[1] + 5]
            fk[1] = fk[1] + 5
            try:
                for i, c in enumerate(ff):
                    c = em(str(i + fk[1] - 5) + c).replace('_', '-')
                    sleep(2)
                    await self.sender.sendMessage(
                        c,
                        parse_mode='Markdown',
                        disable_web_page_preview=True,
                        reply_markup=ReplyKeyboardRemove(remove_keyboard=True))

            except Exception as e:
                print(e)
            if i + fk[1] - 5 < fk[2] - 2 - 10:
                await self._more()
            else:
                await self.sender.sendMessage(
                    'فیدهای این موضوع به اتمام رسید\n برای ادامه مجددا شروع کنید'
                )

        if msg['text'] in ['start', '/start']:
            if msg['text'] == 'start':
                await self.sender.sendMessage(
                    'در حال انجام...',
                    reply_markup=ReplyKeyboardRemove(remove_keyboard=True))
            await self._propose()
예제 #2
0
def on_chat_message(msg):
    content_type, chat_type, chat_id = telepot.glance(msg)
    isPhoto = False
    if content_type == 'text':
        command = msg['text']
        print("Ho ricevuto: " + str(command))
        fn = getattr(pluginCaricati['/rispondi'], 'action')
        ret = fn(command, msg)
        if len(ret) > 0:
            bot.sendMessage(chat_id, ret, reply_markup=ReplyKeyboardRemove())
            print("Rispondo: " + str(ret))

    try:
        toCall = 'action' + ('IsPhoto' if isPhoto else '')
        funz_param = command.split(' ')
        fn = getattr(pluginCaricati[funz_param[0]], toCall)
        ret = fn(funz_param, msg)
        bot.sendMessage(chat_id, ret, reply_markup=ReplyKeyboardRemove())
    except Exception as identifier:
        print("Non esiste nessuna funzione con questo comando:" +
              str(identifier))
    finally:
        # ignora
        pass

    with open('./data/datastory_' + str(id_data) + '.json',
              encoding="utf8") as json_file:
        body = json.load(json_file)
    res = {"message": msg, "reply": ret}
    body['story'].append(res)
    with open('./data/datastory_' + str(id_data) + '.json',
              mode='w',
              encoding='utf8') as json_f:
        json_f.write(json.dumps(body, indent=4))
예제 #3
0
 def branch_one(self, msg, chat_id, from_id):
     lang = self.prev_lang[chat_id]
     topic = self.topic_name[chat_id]
     if self.tree.check_teach(lang, msg["text"]):
         send_message(super().get_bot(),
                      chat_id,
                      self.tree.get_string(lang, "teacher"),
                      reply_markup=ReplyKeyboardRemove())
         self.tree.add_teachers([chat_id], self.topic_name[chat_id],
                                lang)
         del self.topic_name[chat_id]
         del self.prev_lang[chat_id]
     elif self.tree.check_coll(lang, msg["text"]):
         send_message(super().get_bot(),
                      chat_id,
                      self.tree.get_string(lang, "collaborator"),
                      reply_markup=ReplyKeyboardRemove())
         self.tree.add_collaborators([chat_id],
                                     self.topic_name[chat_id], lang)
         del self.topic_name[chat_id]
         del self.prev_lang[chat_id]
     self.singleton_id.start_fun(chat_id, from_id, "private", lang,
                                 self.tree.get_lang(), "teacher", topic,
                                 self.keyboard)
     self.query_bool[chat_id] = False
     self.lang_bool[chat_id] = False
예제 #4
0
def eingekauft(self, msg):
    """
    remove given items from the shopping list
    """
    einkaufsliste = load_einkaufsliste(self)
    if self.eingekauft_flag1:
        item = " ".join(self.command)
        if item == "Alle":
            einkaufsliste = []
            dump_einkaufsliste(self, einkaufsliste)
            self.sender.sendMessage("Einkaufsliste wurde geleert!", reply_markup=ReplyKeyboardRemove())
            telepot.Bot(API_KEY).sendMessage(GROUP_ID, f"{msg['from']['first_name']} hat die Einkaufsliste geleert "
                                                       f"\U0001F4DC\u2705", parse_mode='html')
        elif item == "Abbrechen":
            self.sender.sendMessage("Vorgang abgebrochen.", reply_markup=ReplyKeyboardRemove())
        else:
            try:
                einkaufsliste.remove(item)
                dump_einkaufsliste(self, einkaufsliste)
                self.sender.sendMessage(f"{item} wurde von der Einkaufsliste entfernt!",
                                        reply_markup=ReplyKeyboardRemove())
                telepot.Bot(API_KEY).sendMessage(GROUP_ID, f"{msg['from']['first_name']} hat <b>{item}</b> von der "
                                                           f"Einkaufsliste entfernt \U0001F4DC\u2705",
                                                 parse_mode='html')
            except ValueError:
                {}
        self.eingekauft_flag1 = False
    else:
        if len(einkaufsliste) == 0:
            self.sender.sendMessage("Einkaufsliste ist leer!")
            return
        self.eingekauft_flag1 = True
        self.sender.sendMessage("Welchen Artikel möchtest du entfernen?",
                                reply_markup=create_eingekauft_keyboard(einkaufsliste))
예제 #5
0
def search_station(self):
    """
    helper function for bahn(), skeleton for station searches
    """
    if self.bahn_search3:
        self.bahn_search3 = False
        try:
            user_input = " ".join(self.command)
            if self.search_dest_flag:
                self.search_dest_flag = False
                self.destination = stations[user_input]
                return_search_results(self)
            else:
                self.bahn_destination_flag = True
                self.origin = stations[user_input]
                self.sender.sendMessage("Wo möchtest du hin?", reply_markup=create_bahn_start_keyboard(self))
        except KeyError:
            self.sender.sendMessage("Ungültige Eingabe! Bitte starte die Anfrage noch einmal von vorne.",
                                    reply_markup=ReplyKeyboardRemove())
    elif self.bahn_search2:
        search_result = search_stations(self.command)
        if len(search_result.keys()) > 0:
            keyboard = create_bahn_searchresult_keyboard(search_result)
            self.bahn_search2, self.bahn_search3 = False, True
            self.sender.sendMessage("Bitte wähle eine Station aus:", reply_markup=keyboard)
        else:
            self.sender.sendMessage("Keine Station gefunden. Bitte erneut einen Suchbegriff eingeben:")
    else:
        self.bahn_search, self.bahn_search2 = False, True
        self.sender.sendMessage("Bitte gib einen Suchbegriff ein:", reply_markup=ReplyKeyboardRemove())
예제 #6
0
파일: babylon.py 프로젝트: samson98/babylon
def on_chat_message(msg):
    content_type, chat_type, chat_id = telepot.glance(msg)
    print('Chat:', content_type, chat_type, chat_id)
    command = msg['text'].lower()
    if command == '/start':
        markup2 = ForceReply()
        # keyboard = ReplyKeyboardMarkup(keyboard=[[KeyboardButton(text=''),next key]],resize_keyboard=True)
        markup = InlineKeyboardMarkup(inline_keyboard=[
            [dict(text='How does it work', url='https://telegra.ph/Lists-of-Languages-available-in-the-bot-08-12')]])
        responce = bot.getChat(chat_id)
        first_name = responce['first_name']
        bot.sendChatAction(chat_id, 'typing')
        bot.sendMessage(
            chat_id, f'Hello <b>{first_name} </b>', parse_mode='html', reply_markup=markup2)
        bot.sendChatAction(chat_id, 'typing')
        bot.sendMessage(chat_id, 'Welcome to <b>babylon<b> translator chat bot this bot will help you to translate different languges and helps you to explore more and to communicate better.',
                        parse_mode='html', reply_markup=markup)
    elif msg['text'] != '/start':
        message = msg['text'].lower()
        value = message.split(' ')
        if not '|' in value:
            markup = ReplyKeyboardRemove()
            translator = Translator()
            translation = translator.translate(f'{message}')
            translation_src_name = LANGUAGES[translation.src]
            bot.sendChatAction(chat_id, 'typing')
            bot.sendMessage(
                chat_id, f'Language has been detected <b>{translation_src_name}</b>', parse_mode='html', reply_markup=markup)
            bot.sendChatAction(chat_id, 'typing')
            time.sleep(0.5)
            bot.sendMessage(chat_id, f'{translation.text}', parse_mode='html')
            bot.sendChatAction(chat_id, 'UPLOAD_AUDIO')
            tts = gTTS(message, lang='en')
            tts.save('mk.mp3')
            with open('mk.mp3', 'rb') as speech:
                bot.sendChatAction(chat_id, 'UPLOAD_AUDIO')
                bot.sendVoice(chat_id, voice=speech, caption=None)
                speech.close()
        else:
            try:
                markup = ReplyKeyboardRemove()
                message = msg['text'].lower()
                value = message.split('|')
                user_text = value[0]
                user_dest = value[-1].strip()
                translator = Translator()
                translations = translator.translate(
                    f'{user_text}', dest=f'{user_dest}')
                user_dest_name = LANGUAGES[user_dest]
                user_src_name = LANGUAGES[translations.src]
                bot.sendChatAction(chat_id, 'typing')
                bot.sendMessage(
                    chat_id, f'From <b>{user_src_name}</b> to <b>{user_dest_name}</b>', parse_mode='html')
                bot.sendMessage(
                    chat_id, f'<b>{translations.text}</b>', parse_mode='html')
            except ValueError:
                bot.sendMessage(
                    chat_id, f'invalid destination! what does {user_dest} means see How does it works section!')
예제 #7
0
def edit_weather_favorites(self):
    """
    edit the list of 2 favorite locations saved in the cookie file
    """
    favs = {"Favorit 1": "fav1", "Favorit 2": "fav2"}
    if self.fav_flag3_wetter:
        try:
            self.cookies['wetter']
        except KeyError:
            self.cookies.update({"wetter": {"fav1": {}, "fav2": {}}})
        location_name = " ".join(self.command)
        with open("../../data/weather_locations.json", "rb") as f:
            data = json.load(f)
            locations = [(entry['name'], entry['id']) for entry in data]
        if location_name in [location[0] for location in locations]:
            location_id = [
                location[1] for location in locations
                if location[0] == location_name
            ][0]
            self.cookies['wetter'][self.fav_to_be_modified].clear()
            self.cookies['wetter'][self.fav_to_be_modified].update(
                {location_name: str(location_id)})
            self.fav_flag3_wetter = False
            self.sender.sendMessage("Favorit wurde erfolgreich aktualisiert!",
                                    reply_markup=ReplyKeyboardRemove())
        else:
            self.fav_flag3_wetter = False
            self.sender.sendMessage("Vorgang wurde abgebrochen.",
                                    reply_markup=ReplyKeyboardRemove())
    elif self.fav_flag2_wetter:
        search_result = search_locations(self.command)
        if len(search_result.keys()) > 0:
            keyboard = create_weather_searchresult_keyboard(search_result)
            self.fav_flag2_wetter, self.fav_flag3_wetter = False, True
            self.sender.sendMessage("Bitte wähle einen Standort aus:",
                                    reply_markup=keyboard)
        else:
            self.sender.sendMessage(
                "Kein Standort gefunden. Bitte erneut einen Suchbegriff eingeben:"
            )
    elif self.fav_flag1_wetter:
        entry = " ".join(self.command)
        if entry in favs.keys():
            self.fav_to_be_modified = favs[entry]
            self.fav_flag1_wetter, self.fav_flag2_wetter = False, True
            self.sender.sendMessage("Bitte gib einen Suchbegriff ein:",
                                    reply_markup=ReplyKeyboardRemove())
        else:
            self.fav_flag1_wetter = False
            self.sender.sendMessage("Vorgang wurde abgebrochen.",
                                    reply_markup=ReplyKeyboardRemove())
    else:
        self.fav_flag1_wetter = True
        self.sender.sendMessage("Welchen Eintrag möchtest du bearbeiten?",
                                reply_markup=kb_wetter_favoriten_bearbeiten)
예제 #8
0
    def recebendoMsg(self, msg):
        name = msg['chat']['first_name']
        sentence = str(msg['text'].lower())
        print(sentence, name)
        tipoMsg, tipoChat, chatID = telepot.glance(msg)
        if chatID not in self.__users.keys():
            self.__users[chatID] = {'nome': name, 'pedido': [], 'status': 0}

        if self.__users[chatID]['status'] == 0:
            if sentence == '/start':
                self.inicio(chatID, name)
            else:
                toSend = "Escolha um estabelecimento para começar por favor"
                self.robot.sendMessage(chatID, toSend)
                self.inicio(chatID, name)

        elif self.__users[chatID]['status'] == 1:
            if sentence in self.greetings:
                send = random.choice(self.re_greetings)
                self.robot.sendMessage(chatID, send)
            elif sentence.startswith('/'):
                self.commands(chatID, msg)
            elif sentence in ['não', 'nao', 'no']:
                self.robot.sendMessage(
                    chatID, "Okay, Voce pode pedir outra coisa se quiser.")
            else:
                self.parser(chatID, sentence)
        elif self.__users[chatID]['status'] == 2:
            if sentence in ['sim :)', 'sim', 'si', 'yes', 'quero']:
                self.addProdFinal(chatID)
            elif sentence in ['não', 'nao', 'no']:
                self.__users[chatID]['status'] = 1
                self.robot.sendMessage(
                    chatID,
                    "Okay, Voce pode pedir outra coisa se quiser.",
                    reply_markup=ReplyKeyboardRemove(remove_keyboard=True))
            else:
                self.robot.sendMessage(chatID,
                                       "Por favor, escolha uma opção..")
        elif self.__users[chatID]['status'] == 3:
            if sentence in ['sim ( ͡~ ͜ʖ ͡°)', 'sim :)', 'sim', 'si', 'yes']:
                self.encerraFinal(chatID)
            elif sentence in ['não', 'nao', 'no']:
                self.__users[chatID]['status'] = 1
                self.robot.sendMessage(
                    chatID,
                    "Okay, Voce continuar fazendo seu pedido ;)",
                    reply_markup=ReplyKeyboardRemove(remove_keyboard=True))
            else:
                self.robot.sendMessage(chatID,
                                       "Por favor, escolha uma opção..")
예제 #9
0
def edit_canteen_favorites(self):
    """
    edit the list of 2 favorite canteens saved in the cookie file
    """
    favs = {"Favorit 1": "fav1", "Favorit 2": "fav2"}
    if self.fav_flag3_speiseplan:
        try:
            self.cookies['mensa']
        except KeyError:
            self.cookies.update({"mensa": {"fav1": {}, "fav2": {}}})
        canteen_name = " ".join(self.command)
        if canteen_name in canteens.keys():
            canteen_id = canteens[canteen_name]
            self.cookies['mensa'][self.fav_to_be_modified].clear()
            self.cookies['mensa'][self.fav_to_be_modified].update(
                {canteen_name: canteen_id})
            self.fav_flag3_speiseplan = False
            self.sender.sendMessage("Favorit wurde erfolgreich aktualisiert!",
                                    reply_markup=ReplyKeyboardRemove())
        else:
            self.fav_flag3_speiseplan = False
            self.sender.sendMessage("Vorgang wurde abgebrochen.",
                                    reply_markup=ReplyKeyboardRemove())
    elif self.fav_flag2_speiseplan:
        search_result = search_canteens(self.command)
        if len(search_result.keys()) > 0:
            keyboard = create_canteen_searchresult_keyboard(search_result)
            self.fav_flag2_speiseplan, self.fav_flag3_speiseplan = False, True
            self.sender.sendMessage("Bitte wähle eine Mensa aus:",
                                    reply_markup=keyboard)
        else:
            self.sender.sendMessage(
                "Keine Mensa gefunden. Bitte erneut einen Suchbegriff eingeben:"
            )
    elif self.fav_flag1_speiseplan:
        entry = " ".join(self.command)
        if entry in favs.keys():
            self.fav_to_be_modified = favs[entry]
            self.fav_flag1_speiseplan, self.fav_flag2_speiseplan = False, True
            self.sender.sendMessage("Bitte gib einen Suchbegriff ein:",
                                    reply_markup=ReplyKeyboardRemove())
        else:
            self.fav_flag1_speiseplan = False
            self.sender.sendMessage("Vorgang wurde abgebrochen.",
                                    reply_markup=ReplyKeyboardRemove())
    else:
        self.fav_flag1_speiseplan = True
        self.sender.sendMessage("Welchen Eintrag möchtest du bearbeiten?",
                                reply_markup=kb_canteen_favoriten_bearbeiten)
예제 #10
0
def handle(msg):
        content_type, chat_type, chat_id = telepot.glance(msg)
        print(content_type, chat_type, chat_id)

#    if content_type == 'text':
#        bot.sendMessage(chat_id, "You said '{}'".format(msg["text"]))
        if content_type == 'text':
                if msg['text'] == 'c':
                        bot.sendMessage(chat_id, "Customs", reply_markup=ReplyKeyboardMarkup(keyboard=[[KeyboardButton(text="TEST"), KeyboardButton(text="Close")]]))
                if msg['text'] == 'Close':
                        bot.sendMessage(chat_id, "Closed", reply_markup=ReplyKeyboardRemove())
                if validate_ip(msg['text']):
                        bot.sendMessage(chat_id, "Select what you want to do :"+msg['text'], reply_markup=ReplyKeyboardMarkup(keyboard=[[KeyboardButton(text="Port check:"+msg['text'])], [KeyboardButton(text="Close")]]))
                patt = re.compile('^Port check')
                if patt.match(msg['text']):
                        tmp = ping_test(msg['text'])
                        bot.sendMessage(chat_id, tmp)
                if msg['text'].startswith('dig'):
                        dmn = msg['text'][4:]
                        res = os.popen("sh /home/cobellus/gatest.sh "+dmn).read()
                        bot.sendMessage(chat_id, res)
                p = re.compile('[a-z][a-z][a-z]-')
                if p.match(msg['text']):
                        fds = []
                        xls = pd.ExcelFile('190313_상면_현황.xlsx')
                        for i in range(1, 3):
                                tmp = pd.read_excel(xls, str(i))
                                fds.append(tmp)
                        for df in fds:
                                print (df)
                                if msg['text'] in df['HOST'].values:
                                        td = df.loc[df['HOST'] == msg['text']]
                                        print (td)
                                        res = msg['text'] + "위치: " + str(format(int(td['RACK'].values[0]), '04d')) + "-" + str(td['RACK-UNIT'].values[0])
                                        bot.sendMessage(chat_id, res)
예제 #11
0
    def on_chat_message(self, msg):
        content_type, chat_type, chat_id = telepot.glance(msg)
        if content_type != 'text':
            return

        command = msg['text'].lower()

        if command == '/language':
            stats.increment('language.calls')
            markup = InlineKeyboardMarkup(inline_keyboard=[[
                InlineKeyboardButton(text='Swedish', callback_data='swedish')
            ], [
                InlineKeyboardButton(text='Finnish', callback_data='finnish')
            ], [InlineKeyboardButton(text='English', callback_data='english')]
                                                           ])

            global message_with_inline_keyboard
            message_with_inline_keyboard = self.sender.sendMessage(
                'Select language for menus. Note: selected restaurant may not support your language!',
                reply_markup=markup)

        elif command == 'h':
            markup = ReplyKeyboardRemove()
            self.sender.sendMessage('Hide custom keyboard',
                                    reply_markup=markup)
예제 #12
0
    def send_info(self, username):
        user_data = dbm.get_user_data(username)
        todays_history = dbm.get_todays_history(username)
        team_points, updated_timestamp = dbm.get_team_points()

        team = user_data[TEAM_KEY]
        team_members = ["@" + m for m in dbm.get_team_members(team)]
        n_teams = len(team_points)
        good_list = self.point_dict_to_list(team_points, GOOD_KEY)
        bad_list = self.point_dict_to_list(team_points, BAD_KEY)
        good_idx = next(t[1] for t in good_list if t[0] == team)
        bad_idx = next(t[1] for t in bad_list if t[0] == team)

        team_rank_good = [tname for tname, _ in good_list].index(team) + 1
        team_rank_bad = [tname for tname, _ in bad_list].index(team) + 1

        message_str = INFO_MESSAGE.format(
            username="******" + username,
            team=team,
            team_members=", ".join(team_members),
            team_rank_good=team_rank_good,
            team_rank_bad=team_rank_bad,
            good_index=good_idx,
            bad_index=bad_idx,
            n_teams=n_teams,
            history_str=self.format_user_history(todays_history),
        )
        #print("send_info(): ", message_str)
        self.sender.sendMessage(
            message_str,
            reply_markup=ReplyKeyboardRemove())  #, parse_mode = "markdown")
예제 #13
0
def weather(self):
    """
    general weather function to handle all input
    """
    if self.wetter_flag1 or self.wetter_flag3:
        self.wetter_flag1 = False
        if self.command[0] == "Suche":
            search_weather_skeleton(self)
        elif self.command[0] == "Favoriten" and self.command[1] == "bearbeiten":
            edit_weather_favorites(self)
        else:
            self.wetter_flag3 = False
            try:
                user_input = " ".join(self.command)
                self.destination = user_input
                with open("../../data/weather_locations.json", "rb") as f:
                    data = json.load(f)
                    locations = [(entry['name'], entry['id'])
                                 for entry in data]
                location_id = [
                    location[1] for location in locations
                    if location[0] == user_input
                ]
                return_weather(self, str(location_id[0]))
            except (KeyError, IndexError):
                self.sender.sendMessage(
                    "Ungültige Eingabe! Bitte starte die Anfrage noch einmal von vorne.",
                    reply_markup=ReplyKeyboardRemove())
    else:
        self.wetter_flag1 = True
        keyboard = create_weather_start_keyboard(self)
        self.sender.sendMessage(
            "Zum Abrufen von Wetterdaten bitte einen Standort auswählen:",
            reply_markup=keyboard)
예제 #14
0
def messageSender(chatId, type, msg, *KBList):
    print(chatId, type, msg, *KBList)
    #todo: if have error
    #todo: if kbList is empty
    #todo: change false with return bot.sendMessage()
    if KBList:
        for items in KBList:
            keyboardList = items
    if type == 'text':
        bot.sendMessage(chatId, msg)
    if type == 'keyboard':
        keyboard = ReplyKeyboardMarkup(keyboard=keyboardList)
        bot.sendMessage(chatId, msg, reply_markup=keyboard)
    if type == 'hide':
        keyboard = ReplyKeyboardRemove()
        bot.sendMessage(chatId, msg, reply_markup=keyboard)
    if type == 'reply':
        markup = ForceReply()
        bot.sendMessage(chatId, msg, reply_markup=markup)
    if type == 'button':
        keyboard = InlineKeyboardMarkup(inline_keyboard=keyboardList)
        bot.sendMessage(chatId, msg, reply_markup=keyboard)
    if type == 'forward':
        for k in KBList:
            bot.forwardMessage(chatId, k, msg)
예제 #15
0
 def send_not_coll(self, bot_teacher, lang, lang_class):
     if lang in self.collaborators:
         for coll in self.collaborators[lang]:
             send_message(bot_teacher,
                          coll,
                          lang_class.get_string(lang, "restart"),
                          reply_markup=ReplyKeyboardRemove(selective=False))
예제 #16
0
파일: telebot.py 프로젝트: sj1024/telebot
def handle(msg, chat_id):
    global activemenu
    if chat_id not in ALLOWED_IDS:
        bot.sendMessage(chat_id, 'You are not allowed')
        return
    elif re.match(r'/back', msg):
        if activemenu != home:
            activemenu = activemenu.getparent()
        getInlineButton(chat_id, activemenu.menu())
    elif re.match(r'/start', msg):
        markup = ReplyKeyboardRemove()
        bot.sendMessage(chat_id, 'Starting...', reply_markup=markup)
        activemenu = home
        getInlineButton(chat_id, activemenu.menu())
    else:
        __msg = activemenu.msg(msg)
        if __msg != -1:
            nextmsg = __msg
            if isinstance(nextmsg, Menu):
                activemenu = nextmsg
                getInlineButton(chat_id, activemenu.menu())
            else:
                r = nextmsg
                if type(r) == dict:
                    getInlineButton(chat_id, r)
                else:
                    bot.sendMessage(chat_id, r)
                    getInlineButton(chat_id, activemenu.menu())
        else:
            msg = '\n\nSomething went wrong!'
            bot.sendMessage(chat_id, msg)
            getInlineButton(chat_id, activemenu.menu())
예제 #17
0
파일: Sendinga.py 프로젝트: aerosadegh/rss
    async def on_callback_query(self, msg):
        global RSSFLink, fk, Feeds
        query_id, from_id, query_data = glance(msg, flavor='callback_query')
        if query_data is not '/more':
            from tele import Feeds
            await self._cancel_last()
            await self.sender.sendMessage(RSSFLink[int(query_data)][0] +
                                          em(Feeds[int(query_data)][0]),
                                          reply_markup=ReplyKeyboardRemove())
            ff = Feeds[int(query_data)][1:6]
            fk = [int(query_data), 6, len(Feeds[int(query_data)])]
            try:
                for c in ff:
                    c = em(c).replace('_', '-')
                    sleep(2)
                    await self.sender.sendMessage(
                        c,
                        parse_mode='Markdown',
                        disable_web_page_preview=True,
                    )

            except Exception as e:
                print(e)
            await self._more()
            #self.close()
        else:
            await self.bot.answerCallbackQuery(
                query_id, text='Ok. But I am going to keep asking.')
            await self._cancel_last()
            await self._propose()
예제 #18
0
async def on_chat_message(msg):
    content_type, chat_type, chat_id = telepot.glance(msg)
    print('Chat:', content_type, chat_type, chat_id)

    if content_type != 'text':
        return

    command = msg['text'][-1:].lower()

    if command == 'c':
        markup = ReplyKeyboardMarkup(keyboard=[
                     ['Plain text', KeyboardButton(text='Text only')],
                     [dict(text='Phone', request_contact=True), KeyboardButton(text='Location', request_location=True)],
                 ])
        await bot.sendMessage(chat_id, 'Custom keyboard with various buttons', reply_markup=markup)
    elif command == 'i':
        markup = InlineKeyboardMarkup(inline_keyboard=[
                     [dict(text='Telegram URL', url='https://core.telegram.org/')],
                     [InlineKeyboardButton(text='Callback - show notification', callback_data='notification')],
                     [dict(text='Callback - show alert', callback_data='alert')],
                     [InlineKeyboardButton(text='Callback - edit message', callback_data='edit')],
                     [dict(text='Switch to using bot inline', switch_inline_query='initial query')],
                 ])

        global message_with_inline_keyboard
        message_with_inline_keyboard = await bot.sendMessage(chat_id, 'Inline keyboard with various buttons', reply_markup=markup)
    elif command == 'h':
        markup = ReplyKeyboardRemove()
        await bot.sendMessage(chat_id, 'Hide custom keyboard', reply_markup=markup)
    elif command == 'f':
        markup = ForceReply()
        await bot.sendMessage(chat_id, 'Force reply', reply_markup=markup)
예제 #19
0
def query_employee(message_offset_id, person, bot_obj, query_msg=None):
    his_answer = False
    emp = employee[person]['name']
    keyboard = ReplyKeyboardMarkup(resize_keyboard=True,
                                   one_time_keyboard=True,
                                   keyboard=[
                                       [
                                           KeyboardButton(text="yes",
                                                          callback_data="yes"),
                                           KeyboardButton(text="no",
                                                          callback_data="no")
                                       ],
                                   ])
    if not query_msg:
        query_msg = "{} needs a {}. Are you available?".format(
            "Carl", employee[person]['job'])
    bot_obj.sendMessage(employee[person]['id'],
                        query_msg,
                        reply_markup=keyboard)
    employee_answer, message_offset_id = get_one_message(message_offset_id)

    if "callback_query" in employee_answer:
        markup = ReplyKeyboardRemove()
        bot_obj.sendMessage(employee[person]['id'],
                            "Ok, got it",
                            reply_markup=markup)
        if employee_answer["callback_query"]["data"] == "yes":
            his_answer = emp
    else:
        _, action_type, _ = analyze_request(bot_obj,
                                            employee_answer['message']['text'])
        if action_type == "affermative":
            his_answer = emp
    return his_answer, message_offset_id
예제 #20
0
파일: sender.py 프로젝트: igorB88/pomodoro
    def to_telegram_markup(self):
        result = None
        if self.remove_menu:
            result = ReplyKeyboardRemove(remove_keyboard=True)
        elif self.buttons:
            keyboard = []
            for markup_row in self.buttons:
                row = []
                for markup_button in markup_row:
                    row.append(
                        KeyboardButton(
                            text=markup_button.text,
                            request_contact=markup_button.request_contact))
                keyboard.append(row)
            result = ReplyKeyboardMarkup(keyboard=keyboard)
        elif self.inline_buttons:
            keyboard = []
            for markup_row in self.inline_buttons:
                row = []
                for markup_button in markup_row:
                    if markup_button.url:
                        row.append(
                            InlineKeyboardButton(text=markup_button.text,
                                                 url=markup_button.url))
                    elif markup_button.data:
                        callback = json.dumps(markup_button.data)
                        row.append(
                            InlineKeyboardButton(text=markup_button.text,
                                                 callback_data=callback))

                keyboard.append(row)
            result = InlineKeyboardMarkup(inline_keyboard=keyboard)
        return result
예제 #21
0
파일: bot.py 프로젝트: PinLin/KCOJ_bot
 def input_password(self, text):
     self.question = None
     self.status = '輸入密碼'
     self.username = text
     # 發送訊息
     bot.sendMessage(self.uid, "輸入完可刪除訊息以策安全!\n請輸入您的密碼:",
                     reply_markup=ReplyKeyboardRemove())
예제 #22
0
 def set_lang(self, chat_id, from_id, lang, chat_type):
     user = super().get_bot().getChat(from_id)
     lang_array = self.get_lang_array()
     if len(lang_array) > 0:
         self.singleton.add_time_id(chat_type, self.node.get_lang(), lang,
                                    from_id, chat_id, 4,
                                    self.node.get_topic_name())
         send_message(super().get_bot(),
                      chat_id,
                      tag_group(chat_type, user) +
                      self.node.get_string(lang, "lang"),
                      self.node.get_string(lang, "canc"),
                      self.singleton.check_time_id(
                          chat_type, self.node.get_lang(), lang, from_id,
                          chat_id, self.node.get_topic_name()) != 0,
                      reply_markup=self.node.set_lang_keyboard(lang_array))
     else:
         send_message(super().get_bot(),
                      chat_id,
                      tag_group(chat_type, user) +
                      self.node.get_string(lang, "disable"),
                      self.node.get_string(lang, "canc"),
                      self.singleton.check_time_id(
                          chat_type, self.node.get_lang(), lang, from_id,
                          chat_id, self.node.get_topic_name()) != 0,
                      reply_markup=ReplyKeyboardRemove())
예제 #23
0
 def send_not_stud(self, lang, lang_class):
     if lang in self.students:
         for stud in self.students[lang]:
             send_message(super().get_bot(),
                          stud,
                          lang_class.get_string(lang, "restart"),
                          reply_markup=ReplyKeyboardRemove(selective=False))
예제 #24
0
def send_meal_plan(self, canteen_id):
    """
    make API request to OpenMensa, format response and send response message to user
    """
    current_time = datetime.now()
    if int(datetime.now().strftime("%H")) > 14:
        tomorrow = current_time + timedelta(days=1)
        date = tomorrow.strftime("%Y-%m-%d")
        msg = f"Speiseplan für morgen, den {tomorrow.strftime('%d.%m.%Y')}: \n\n"
    else:
        date = "today"
        msg = f"Speiseplan für heute, den {current_time.strftime('%d.%m.%Y')}: \n\n"
    meal_plan = extract_from_api_request(
        make_api_request(str(canteen_id), date))
    if meal_plan == -2:
        msg = msg + "Leider kein Angebot!"
    elif meal_plan == -1:
        msg = msg + "Fehler beim Abrufen des Speiseplans!"
    else:
        for key in meal_plan.keys():
            msg += f"<b>{key}:</b>\n\n"
            for meal, price in meal_plan[key].items():
                msg += f"{meal}\n<b>{price}</b>\n\n"
            msg += "\n"
    self.sender.sendMessage(msg,
                            parse_mode='html',
                            reply_markup=ReplyKeyboardRemove())
예제 #25
0
 def send_not_teach(self, bot_teacher, lang, lang_class):
     if lang in self.teachers:
         for teach in self.teachers[lang]:
             send_message(bot_teacher,
                          teach,
                          lang_class.get_string(lang, "restart"),
                          reply_markup=ReplyKeyboardRemove(selective=False))
예제 #26
0
파일: botisfy.py 프로젝트: Wend3r/telepot-1
def on_chat_message(msg):
    content_type, chat_type, chat_id = telepot.glance(msg)
    print('Chat:', content_type, chat_type, chat_id)
    command = msg['text'].lower()
    if command == '/start':
        responce = bot.getChat(chat_id)
        global first_name
        global user_name
        global user_id
        global c_type
        global bio
        first_name = responce['first_name']
        user_name = responce['username']
        bot.sendChatAction(chat_id, 'typing')
        user_id = responce['id']
        user_name = responce['username']
        c_type = responce['type']
        bio = responce['bio']
        markup2 = ReplyKeyboardMarkup(keyboard=[
            ['🔰accept and proceed'],
        ],
                                      resize_keyboard=True)
        bot.sendPhoto(
            chat_id,
            photo="https://images.app.goo.gl/joSrXdbBYpesQt7o6",
            caption=
            f'<b>Hello {first_name}!</b> {user_id} \nMSG91 is a cloud communication platform that offers powerful messaging solutions to empower business communications. It consists of 10+ channels across the platform offering services over SMS.',
            parse_mode='html',
            reply_markup=markup2)
    if command == '🔰accept and proceed' or command == 'a':
        markup = ReplyKeyboardRemove()
        bot.sendMessage(chat_id,
                        '<b>Text:</b> for recipient:',
                        parse_mode='html',
                        reply_markup=markup)
예제 #27
0
 def customkeyboard(choice1, choice2, chat, chat_id):
     markup = ReplyKeyboardRemove()
     bot.sendMessage(chat_id, 'Oke lah, got it!', reply_markup=markup)
     markup = ReplyKeyboardMarkup(keyboard=[
         [choice1, KeyboardButton(text=choice2)],
     ],
                                  resize_keyboard=True)
     bot.sendMessage(chat_id, chat, reply_markup=markup)
예제 #28
0
async def on_chat_message(msg):
    content_type, chat_type, chat_id = telepot.glance(msg)
    print("Chatting in {} with {}".format(chat_type, chat_id))

    if (content_type != "text"):
        return()

    cmd = msg['text'].lower()

    amount = 0
    try:
        amount = int(cmd)
    except ValueError:
        pass

    if cmd == '/help':
        await bot.sendMessage(chat_id, 'Type /arb to simulate an arbitrage position')

    elif cmd == '/arb':
        kybrd = ReplyKeyboardMarkup(keyboard=[
            [KeyboardButton(text='BTC'),
            KeyboardButton(text='ETH')],
        ])

        await bot.sendMessage(chat_id, 'Which asset would you like to buy', reply_markup=kybrd)

    elif cmd in ['btc', 'eth']:
        global token
        token = cmd.upper()

        kybrd = ReplyKeyboardMarkup(keyboard=[
            [KeyboardButton(text='EUR'),
            KeyboardButton(text='USD')],
        ])

        await bot.sendMessage(chat_id, 'Which forex asset would you like to use', reply_markup=kybrd)
    elif cmd in ['usd', 'eur']:
        global buy_currency

        buy_currency = cmd.upper()

        kybrd = ReplyKeyboardRemove()
        await bot.sendMessage(chat_id, "How much ZAR do you want to spend on {}?".format(token), reply_markup=kybrd)

    elif amount > 0:
        await bot.sendMessage(chat_id, "Simulating {} ZAR for {} via {}...".format(amount, token, buy_currency))

        forex_ex = FNB(buy_currency)
        buy_ex = GDAX(CB_KEY, CB_SECRET, buy_currency, token)
        sell_ex = Luno(LUNO_KEY,LUNO_SECRET, currency_from="ZAR", currency_to=token)

        profit, margin = arbitrage(amount, buy_ex, sell_ex, forex_ex=forex_ex, forex_fees=True, verbose=False)

        await bot.sendMessage(chat_id, "Arbitrage of {:.2f} would yield {:.2f} profit.\nCurrent margin is {:.2f}".format(amount, profit, margin),
            reply_to_message_id=msg['message_id'])

    else:
        print('Ooops')
예제 #29
0
 def location(chat_id):
     markup = ReplyKeyboardRemove()
     keyboard = ReplyKeyboardMarkup(keyboard=[[
         KeyboardButton(text='Sure! Send My Location',
                        request_location=True)
     ]],
                                    resize_keyboard=True,
                                    one_time_keyboard=True)
     bot.sendMessage(chat_id, 'Give location?', reply_markup=keyboard)
예제 #30
0
    def post(self, request, bot_token):
        if bot_token != settings.TELEGRAM_BOT_TOKEN:
            return HttpResponseForbidden('Invalid token')
        commands = {
            '/start': _display_help,
            'help': _display_help,
            'feed': _display_planetpy_feed,
            '/getworkspaces': _get_all_workspaces,
        }

        raw = request.body.decode('utf-8')
        logger.info(raw)

        try:
            payload = json.loads(raw)
        except ValueError:
            return HttpResponseBadRequest('Invalid request body')

        else:
            try:
                if 'document' in payload['message']:
                    document = payload['message']['document']
                    if payload['message']['document']['thumb']['file_path']:
                        file_path = str(
                            "https://api.telegram.org/file/bot402840205:AAHyxQfL_OeXiVwNSQkV2v1dJvQcmhlir5g/"
                            + payload['message']['document']['thumb']
                            ['file_path'])
                        files = urllib2.urlopen(file_path)
            except urllib2.URLError, e:
                pass
            buttons = []
            if 'message' in payload.keys():
                chat_id = payload['message']['chat']['id']
                cmd = payload['message'].get('text')  # command

            if cmd and cmd == "/start":
                buttons.append([KeyboardButton(text="nroer.gov.in")])
                buttons.append([KeyboardButton(text="abcde.metastudio.org")])

                TelegramBot.sendMessage(
                    chat_id,
                    "Welcome to gstudio please select websites to connect",
                    reply_markup=ReplyKeyboardMarkup(keyboard=buttons))

            if cmd and cmd == "nroer.gov.in":
                site_var = "http://nroer.gov.in"
                response = requests.get("http://nroer.gov.in/api/v1/workspace")
                rc = eval(unicode(response.content, 'utf_16'))
                TelegramBot.sendMessage(
                    chat_id,
                    "Please upload file!",
                    reply_markup=ReplyKeyboardRemove(remove_keyboard=True))

            if cmd and cmd == "abcde.metastudio.org":
                site_var = "abcde.metastudio.org"
                TelegramBot.sendMessage(chat_id, site_var)