def dialog_answer_buttons_1():
    keyboard = ReplyKeyboardMarkup(
        keyboard=[[KeyboardButton(text="Осмотреть храм")]])
    return keyboard
Exemple #2
0
    def on_chat_message(self, msg):
        content_type, chat_type, chat_id = telepot.glance(msg)
        print(content_type, chat_type, chat_id)

        # get available buttons for keyboard
        food_pref = menu.keys()

        # when user wants to find nearest canteen, use Google Maps API to get details to get there
        if content_type == 'location':
            x = msg['location']['latitude']
            y = msg['location']['longitude']
            #parse location from telegram and change into gmaps format
            origins = [[x, y]]
            destinations = [[1.346628, 103.686028], [1.348363, 103.685482],
                            [1.344189, 103.685439], [1.352270, 103.685298],
                            [1.354908, 103.686477], [1.351721, 103.681082],
                            [1.352692, 103.682108], [1.350299, 103.680914],
                            [1.354395, 103.688173], [1.347029, 103.680254],
                            [1.342459, 103.682427], [1.348746, 103.677614]]
            # nearest canteen determined
            n = Nearest_Canteen(x, y)
            listz = (GetAllDistance_Canteen(origins, destinations))
            distance_timetowalk = listz[
                n]  # extract time and duration for the nearest canteen
            menu_response = ('The nearest food location is ' + canfood[n] +
                             '.\nIt is approximately ' +
                             distance_timetowalk[0] +
                             ' away\nWhich is about ' +
                             distance_timetowalk[1] + ' if you walk.')
            menu_keyboard = ReplyKeyboardMarkup(
                one_time_keyboard=True,
                keyboard=[[KeyboardButton(text=pref)]
                          for pref in food_pref] + [[
                              KeyboardButton(text='Find Nearest Canteen',
                                             request_location=True)
                          ]])

            bot.sendMessage(chat_id, menu_response, reply_markup=menu_keyboard)
            bot.sendMessage(
                chat_id, 'What can I do for you?'
            )  # added this line to get user to choose options again if required

            # move to second state for user to choose options
            self.state = choose_second_button
        else:

            try:

                #initial response when bot is started
                if msg['text'] == '/start' or self.state == 0:  # consider /start for resetting bot

                    response = 'Welcome to NTU Food Bot!\nFood decisions are very personal,\nso I will only work in private chats!!'

                    bot.sendMessage(chat_id, response)

                    # prepare custom keyboard
                    choose_first_keyboard = ReplyKeyboardMarkup(
                        one_time_keyboard=True,
                        keyboard=[[KeyboardButton(text=pref)]
                                  for pref in food_pref] +
                        [[
                            KeyboardButton(text='Find Nearest Canteen',
                                           request_location=True)
                        ]])

                    response = 'What can I do for you?'

                    bot.sendMessage(chat_id,
                                    response,
                                    reply_markup=choose_first_keyboard)

                    # move to next state
                    self.state = choose_second_button

                # to avoid repeating welcome message after bot is started
                elif (self.state > choose_first_button):

                    msg_text = msg['text']
                    # placeholders for keyboard and response
                    menu_keyboard = ReplyKeyboardMarkup(
                        one_time_keyboard=True,
                        keyboard=[[KeyboardButton(text=pref)]
                                  for pref in food_pref] +
                        [[
                            KeyboardButton(text='Find Nearest Canteen',
                                           request_location=True)
                        ]])
                    menu_response = ''

                    #separate into different functions when different buttons are selected
                    if (self.state == choose_second_button):

                        #when food preference is chosen
                        if 'Preference' in msg_text:

                            #update context preference for later re-use
                            self.pref = msg_text

                            #load list of canteens for the chosen preference
                            which_canteen = menu[self.pref]

                            #prepare keyboard and response to get user selection of canteen
                            menu_keyboard = ReplyKeyboardMarkup(
                                one_time_keyboard=True,
                                keyboard=[[KeyboardButton(text=canteens)]
                                          for canteens in which_canteen.keys()
                                          ] +
                                [[KeyboardButton(text='Return to main menu')]])

                            menu_response = 'Which canteen?'

                            # move to next state
                            self.state = choose_third_button

                        #when user want to give review about a stall
                        elif 'Give/Check stall rating' in msg_text:

                            #load list of canteens for review
                            which_canteen = menu['Give/Check stall rating']

                            # prepare keyboard and response to get user selection of canteen
                            menu_keyboard = ReplyKeyboardMarkup(
                                one_time_keyboard=True,
                                keyboard=[[KeyboardButton(text=canteens)]
                                          for canteens in which_canteen.keys()
                                          ] +
                                [[KeyboardButton(text='Return to main menu')]])

                            menu_response = 'Which canteen?'

                            # move to next state
                            self.state = review_stall_button

                    #for user to choose what food type they prefer
                    elif (self.state == choose_third_button):

                        if msg_text != 'Return to main menu':

                            # update context canteen for later re-use
                            self.can = msg_text

                            # load list of food types for the chosen canteen
                            what_food_type = menu[self.pref][self.can]

                            # prepare keyboard and response to get user selection of food type
                            menu_keyboard = ReplyKeyboardMarkup(
                                one_time_keyboard=True,
                                keyboard=[[KeyboardButton(text=stalls)]
                                          for stalls in what_food_type.keys()
                                          ] +
                                [[KeyboardButton(text='Return to main menu')]])

                            menu_response = 'What food type?'

                            # move to next state
                            self.state = list_stalls

                        else:

                            menu_response = 'What can I do for you?'

                            self.state = choose_second_button

                    #return list of stalls for the chosen food type
                    elif (self.state == list_stalls):

                        if msg_text != 'Return to main menu':

                            # update context food type for later re-use
                            self.type = msg_text

                            # load list of stalls for the chosen food type
                            menu_response = menu[self.pref][self.can][
                                self.type]

                            # move to second state for user to choose options
                            self.state = choose_second_button

                            bot.sendMessage(chat_id,
                                            menu_response,
                                            reply_markup=menu_keyboard)
                            bot.sendMessage(
                                chat_id, 'What can I do for you?'
                            )  # added this line to get user to choose options again if required
                            return

                        else:

                            menu_response = 'What can I do for you?'

                            self.state = choose_second_button

                    #for user to choose stall
                    elif (self.state == review_stall_button):

                        if msg_text != 'Return to main menu':

                            # update context canteen for later re-use
                            self.can = msg_text

                            # load list of stalls for the chosen canteen
                            which_stall = menu['Give/Check stall rating'][
                                self.can]

                            # prepare keyboard and response to get user selection of stall
                            menu_keyboard = ReplyKeyboardMarkup(
                                one_time_keyboard=True,
                                keyboard=[[KeyboardButton(text=stalls)]
                                          for stalls in which_stall.keys()] +
                                [[KeyboardButton(text='Return to main menu')]])

                            menu_response = 'Which stall?'

                            # move to next state
                            self.state = review_give_ratings

                        else:

                            menu_response = 'What can I do for you?'

                            self.state = choose_second_button

                    #for user to enter rating for stall
                    elif (self.state == review_give_ratings):

                        if msg_text != 'Return to main menu':

                            # update context stall for later re-use
                            self.stall = msg_text

                            # obtain the position of the stall in the ratings lists from the dictionary
                            list_pos = menu['Give/Check stall rating'][
                                self.can][self.stall]

                            # prepare keyboard and response to get user rating of stall from 1 to 5
                            menu_keyboard = ReplyKeyboardMarkup(
                                one_time_keyboard=True,
                                keyboard=[[KeyboardButton(text=rating)]
                                          for rating in range(1, 6)] +
                                [[KeyboardButton(text='Return to main menu')]])

                            response = (
                                'The current rating for the stall is ' +
                                str(rating_avg[list_pos]) + 'тнР')

                            menu_response = "Please choose your rating for the stall.\nIf you don't want to give a rating, press 'Return to main menu'."

                            bot.sendMessage(chat_id, response)

                            # move to next state
                            self.state = review_get_rating

                            # store position in list
                            self.stallkey = list_pos

                        else:

                            menu_response = 'What can I do for you?'

                            self.state = choose_second_button

                    #for updating user rating to the rating database
                    elif (self.state == review_get_rating):

                        if msg_text != 'Return to main menu':

                            # update context rating for later re-use
                            self.rating = msg_text

                            # update numerator with addition of user rating
                            rating_num[self.stallkey] = rating_num[
                                self.stallkey] + int(self.rating)

                            # update denominator with addition of user rating
                            rating_div[self.stallkey] += 1

                            # obtain new average rating
                            before_rounding = rating_num[
                                self.stallkey] / rating_div[self.stallkey]

                            # round up value of average rating as accuracy required is only 1 decimal place, so round function is adequate
                            rating_avg[self.stallkey] = round(
                                before_rounding, 2)

                            # thank user for their rating
                            menu_response = 'Thank you for your review!'

                            # move to second state for user to choose options
                            self.state = choose_second_button

                            bot.sendMessage(chat_id,
                                            menu_response,
                                            reply_markup=menu_keyboard)
                            bot.sendMessage(
                                chat_id, 'What can I do for you?'
                            )  # added this line to get user to choose options again if required
                            return

                        else:

                            menu_response = 'What can I do for you?'

                            self.state = choose_second_button

                    bot.sendMessage(chat_id,
                                    menu_response,
                                    reply_markup=menu_keyboard)
                    return

            except:  # edge case, if user use their normal keyboard instead of custom keyboards
                bot.sendMessage(chat_id,
                                'Error, please use the keyboard provided!')
Exemple #3
0
# importaçao das bibliotecas que estao sendo usadas
import time
import telepot
import urllib2
import commands
from telepot.namedtuple import ReplyKeyboardMarkup, KeyboardButton, ReplyKeyboardRemove

# Aqui e o teclado que aparece para o usuario
# as palavras do teclado sao os comanos
# que seram enviadas para a estrutura de decisao
keyboard = ReplyKeyboardMarkup(keyboard=[
    [KeyboardButton(text="Temperatura"),
     KeyboardButton(text="Processos")],
    [KeyboardButton(text="Memoria"),
     KeyboardButton(text="UpTime")],
    [KeyboardButton(text="UsoSD"),
     KeyboardButton(text="Data")],
    [KeyboardButton(
        text="Rede"), KeyboardButton(text="IP")],
])

#aqui estao as constantes para controle colcoar o bot API aqui agora
CHAT_ADMIN = 345318600
BOT_API = ' '
CHAT_AUTHORIZED_1 = 83074778
CHAT_AUTHORIZED_2 = 24774270


# primeira função que inicia o bot quando
# clicado em começar ou enviado /start
# envia messagens de boas vindas e ativa o teclado
Exemple #4
0
import datetime  # Importing the datetime library
import telepot   # Importing the telepot library
from telepot.loop import MessageLoop    # Library function to communicate with telegram bot
from time import sleep      # Importing the time library to provide the delays in program
import picamera
import time
import os
from telepot.namedtuple import ReplyKeyboardMarkup, KeyboardButton, ReplyKeyboardRemove, ForceReply
from telepot.namedtuple import InlineKeyboardMarkup, InlineKeyboardButton

markup = ReplyKeyboardMarkup(keyboard=[
                     ['Hi', KeyboardButton(text='How you doin?')],
                     [dict(text='Picture Time'), KeyboardButton(text='Live feed')],
                     [dict(text='Upcoming feature1'), KeyboardButton(text='Upcoming feature2')]
                        ])

video_reply = ReplyKeyboardMarkup(keyboard=[
                     ['5', KeyboardButton(text='10')],
                     [dict(text='15'), KeyboardButton(text='Back')],
                        ])

p_res={1024,768}        #Photo resolution
v_res={640,480}         #Video resolution
p_name= "click"         #Name for photo file
v_name= "video"         #Name for video file

#get your own token from Telegram, it's easy
telegram_key='Enter your Telegram Token'


def handle(msg):
    def on_chat_message(self, msg):
        content_type, chat_type, chat_id = telepot.glance(msg)
        command = msg['text']
        conn = sqlite3.connect("weather_data.db")
        cursor = conn.cursor()

        if command == 'data from sensors':
            try:
                cursor.execute("""select temperature,pressure,
                humidity from data order by id desc LIMIT 1""")
            except sqlite3.DatabaseError as err:
                self.bot.sendMessage(
                    admin, "ошибка с чтением из базы данных " + str(err))
            temp, pres, humi, = cursor.fetchone()
            print(temp, pres, humi)
            self.sender.sendMessage("temperature: " +
                                    str("%.2f" % round(temp, 2)) + " C")
            self.sender.sendMessage("pressure: " +
                                    str("%.2f" % round(pres, 2)) + " mm Hg")
            self.sender.sendMessage("humidity: " +
                                    str("%.2f" % round(humi, 2)) + " %")
        elif command == 'weather now':
            try:
                cursor.execute(
                    "select pressure from data order by id desc LIMIT 1")
            except sqlite3.DatabaseError as err:
                self.bot.sendMessage(
                    admin, "ошибка с чтением из базы данных " + str(err))
            pres, = cursor.fetchone()
            self.sender.sendMessage("here weather for now:")
            self.sender.sendMessage(self.weather_now(pres))
        elif command == 'weather predict':
            arr = list()
            timestamp = datetime.datetime.now().timestamp()
            sql = "select pressure from data where timestamp between "
            sql += str(timestamp - 36000) + " and " + str(timestamp)
            try:
                for row in cursor.execute(sql):
                    arr.append(row[0])
            except sqlite3.DatabaseError as err:
                self.bot.sendMessage(
                    admin, "ошибка с чтением из базы данных " + str(err))
            if len(arr) < 7:
                self.sender.sendMessage(
                    "Sorry, we don't have actual data right now")
                self.bot.sendMessage(admin, "Нет данных за последние 10 часов")
            else:
                sumX = 0
                sumY = 0
                sumX2 = 0
                sumXY = 0
                for i in range(0, len(arr)):
                    sumX += i
                    sumX2 += i * i
                    sumY += arr[i]
                    sumXY += arr[i] * i
                delta = len(arr) * sumXY - sumX * sumY
                delta /= (len(arr) * sumX2 - sumX * sumX)
                delta *= len(arr)
                self.sender.sendMessage("here weather predict for now:")
                self.sender.sendMessage(self.weather_predict(delta))
        elif command == 'statistic':
            self.markup = ReplyKeyboardMarkup(keyboard=[
                [dict(text='day')],
                [dict(text='3 days')],
                [dict(text='week')],
                [dict(text='mounth')],
                [dict(text='back to main')],
            ])
            self.sender.sendMessage(command, reply_markup=self.markup)
        elif (command == 'day') or (command == '3 days') or (
                command == 'week') or (command == 'mounth'):
            self.markup = ReplyKeyboardMarkup(keyboard=[
                [dict(text='temperature')],
                [dict(text='pressure')],
                [dict(text='humidity')],
                [dict(text='back to main')],
            ])
            self.sender.sendMessage(command, reply_markup=self.markup)
            if command == 'day': self.ttime = 86400
            if command == '3 days': self.ttime = 259200
            if command == 'week': self.ttime = 604800
            if command == 'mounth': self.ttime = 2592000
        elif command == 'back to main':
            self.markup = ReplyKeyboardMarkup(keyboard=[
                [dict(text='data from sensors')],
                [dict(text='weather now')],
                [dict(text='weather predict')],
                [dict(text='statistic')],
            ])
            self.sender.sendMessage(command, reply_markup=self.markup)
        elif command == 'temperature':
            y = list()
            x = list()
            timestamp = datetime.datetime.now().timestamp()
            sql = "select timestamp, temperature from data where timestamp between "
            sql += str(timestamp - self.ttime) + " and " + str(timestamp)
            try:
                for row in cursor.execute(sql):
                    x.append(datetime.datetime.fromtimestamp(row[0]))
                    y.append(row[1])
            except sqlite3.DatabaseError as err:
                self.bot.sendMessage(
                    admin, "ошибка с чтением из базы данных " + str(err))
            plt.figure()
            plt.plot(x, y)
            plt.tight_layout()
            plt.savefig('foo.png')
            self.sender.sendPhoto(open('foo.png', 'rb'))
        elif command == 'pressure':
            y = list()
            x = list()
            timestamp = datetime.datetime.now().timestamp()
            sql = "select timestamp, pressure from data where timestamp between "
            sql += str(timestamp - self.ttime) + " and " + str(timestamp)
            try:
                for row in cursor.execute(sql):
                    x.append(datetime.datetime.fromtimestamp(row[0]))
                    y.append(row[1])
            except sqlite3.DatabaseError as err:
                self.bot.sendMessage(
                    admin, "ошибка с чтением из базы данных " + str(err))
            plt.figure()
            plt.plot(x, y)
            plt.tight_layout()
            plt.savefig('foo.png')
            self.sender.sendPhoto(open('foo.png', 'rb'))
        elif command == 'humidity':
            y = list()
            x = list()
            timestamp = datetime.datetime.now().timestamp()
            sql = "select timestamp, humidity from data where timestamp between "
            sql += str(timestamp - self.ttime) + " and " + str(timestamp)
            try:
                for row in cursor.execute(sql):
                    x.append(datetime.datetime.fromtimestamp(row[0]))
                    y.append(row[1])
            except sqlite3.DatabaseError as err:
                self.bot.sendMessage(
                    admin, "ошибка с чтением из базы данных " + str(err))
            plt.figure()
            plt.plot(x, y)
            plt.tight_layout()
            plt.savefig('foo.png')
            self.sender.sendPhoto(open('foo.png', 'rb'))
Exemple #6
0
def handle(msg):  #Wait message from user in telegram
    bot = telepot.Bot(TOKEN_BOT)
    user_id = msg["from"]["username"]
    chat_id = msg["chat"]["id"]
    command = msg["text"]

    counter = 0
    dict_switches_id = {}
    dict_switches_name = {}
    for item in requests.get(
            url="http://localhost:8090/api/switches").json()["switches"]:
        counter += 1
        dict_switches_id["Switch{0}".format(counter)] = str(item["id"])
        dict_switches_name["Switch{0}".format(counter)] = str(item["name"])

    #counter = 0
    #dict_switches_name = {}
    #for item in requests.get(url = "http://localhost:8090/api/switches").json()["switches"]:
    #counter += 1
    #dict_switches_name["Switch{0}".format(counter)] = str(item["name"])

    print "Got command: %s" % command

    #Check whitelist
    if user_id not in users:
        bot.sendMessage(chat_id, "F**k off")
        return

#Date, time, week number/day of year
    if command == "/time":
        bot.sendMessage(
            chat_id,
            str(datetime.datetime.now().strftime(
                "Current date and time:\n%d %B %Y %H:%M \nWeek number of year: %W \nDay of year: %j"
            )))

#Simple calendar on month
    elif command == '/calendar':
        calendar_print = calendar.LocaleTextCalendar(
            firstweekday=0,
            locale="ru_RU.UTF-8").formatmonth(current_year, current_month, 0,
                                              0).encode("utf8")
        #Print in terminal or in log(nohup.out) if you execute - "nohup BOT.py &"
        print(calendar_print)
        #Send message to user
        bot.sendMessage(chat_id,
                        text=str("<pre>" + calendar_print + "</pre>"),
                        parse_mode="HTML")

#Main menu
    elif command == "/test" or command == "Return to Main Menu":
        bot.sendMessage(
            chat_id,
            "Choose your destiny...",
            reply_markup=ReplyKeyboardMarkup(keyboard=[
                [KeyboardButton(text="Summary information")],
                [KeyboardButton(text="Alerts"),
                 KeyboardButton(text="Photo")],
                [
                    KeyboardButton(text="Management"),
                    KeyboardButton(text="Administration")
                ],
                [KeyboardButton(text="Other tools")],
            ]))

#Info about raspberry pi
    elif command == "/status":
        api_req_get_status_rpi = requests.get(
            url="http://localhost:8090/api/system").json()
        for_print = str(
            "Terrarium Pi works about ~" +
            format(api_req_get_status_rpi["uptime"] / 60 / 60, ".1f") +
            " hours"
            "\nTemperature on board: " +
            format(api_req_get_status_rpi["temperature"], ".2f") + " C" +
            "\nFree memory is " +
            format(api_req_get_status_rpi['memory']['free'] / 1024 /
                   1024, ".1f") + " MB" + " of total " +
            format(api_req_get_status_rpi['memory']['total'] / 1024 /
                   1024, ".1f") + " MB")

        #Print in terminal or in log(nohup.out) if you execute - "nohup BOT.py &"
        print(for_print)
        #Send message to user
        bot.sendMessage(chat_id, for_print)

#Menu - "Summary information"
    elif command == "Summary information":
        #Variables for this command:
        api_req_get_sensors = requests.get(
            url="http://localhost:8090/api/sensors").json()["sensors"]
        api_req_get_doors = requests.get(
            url="http://localhost:8090/api/doors").json()["doors"]
        for_print = ""
        #Cycle for collect info about sensors:
        for item in api_req_get_sensors:
            for_print += str("On " + item["hardwaretype"] + " " +
                             item["type"] + " is " +
                             format(item["current"], ".2f") +
                             item["indicator"] + "\n")
        #Cycle for alert about "open" door:
        for item in api_req_get_doors:
            if str(item["state"]) == "open":
                for_print += str(item["name"] + " is " + item["state"] + " !")
        #Print in terminal or in log(nohup.out) if you execute - "nohup BOT.py &"
        print(for_print)
        #Send message to user
        bot.sendMessage(chat_id, for_print)

#Menu - "Alerts"
    elif command == "Alerts" or command == "Update information about alerts":
        #Variables for this command:
        api_req_get_sensors = requests.get(
            url="http://localhost:8090/api/sensors").json()["sensors"]
        api_req_get_doors = requests.get(
            url="http://localhost:8090/api/doors").json()["doors"]
        for_print = ""
        #Cycle for collect info about sensor whose data over "alarm_min" and "alarm_max"
        for item in api_req_get_sensors:
            if str(item["alarm"]) == "True":
                if item["current"] < item["alarm_min"]:
                    for_print += str("Too low " + item["type"] + " on " +
                                     item["name"] + ": " +
                                     format(item["current"], ".2f") + " !\n")
                if item["current"] > item["alarm_max"]:
                    for_print += str("Too high " + item["type"] + " on " +
                                     item["name"] + ": " +
                                     format(item["current"], ".2f") + " !\n")
        #Cycle for alert about "open" door:
        for item in api_req_get_doors:
            if str(item["state"]) == "open":
                for_print += str(item["name"] + " is " + item["state"] + " !")
        #Print in terminal or in log(nohup.out) if you execute - "nohup BOT.py &"
        print(for_print)
        #Send message to user
        bot.sendMessage(chat_id, for_print)
        bot.sendMessage(
            chat_id,
            "UNDER CONSTRUCTION",
            reply_markup=ReplyKeyboardMarkup(keyboard=[
                [
                    KeyboardButton(text="Turn OFF VCC")
                ],  #At this point there should be a switch which disconnect main electricity(relay before of socket block)
                [KeyboardButton(text="Update information about alerts")],
                [KeyboardButton(text="Return to Main Menu")],
            ]))

#Menu - "Photo"
    elif command == "Photo" or command == "Shoot new photo":
        camera = PiCamera()
        camera.resolution = (640, 480)
        camera.annotate_text_size = 22
        camera.annotate_text = str(
            datetime.datetime.now().strftime("%d %B %Y %H:%M"))
        camera.capture("/home/pi/capt_for_bot.jpg")
        time.sleep(5)
        camera.close()
        bot.sendPhoto(chat_id,
                      photo=open("/home/pi/capt_for_bot.jpg", "rb"),
                      reply_markup=ReplyKeyboardMarkup(keyboard=[
                          [KeyboardButton(text="Shoot new photo")],
                          [KeyboardButton(text="Return to Main Menu")],
                      ]))

#Menu - "Management"
    elif command == "Management" or command == "Update information about switches":
        api_req_get_switches = requests.get(
            url="http://localhost:8090/api/switches").json()["switches"]
        for_print = ""
        for item in api_req_get_switches:
            if str(item["state"]) == "True":
                for_print += str(item["name"] + " is now: ON\n")
            if str(item["state"]) == "False":
                for_print += str(item["name"] + " is now: OFF\n")
        print(for_print)
        #Dictionary of four name and IDs switches for buttons in my variant
        counter = 0
        dict_switches_name = {}
        dict_switches_id = {}
        for item in api_req_get_switches:
            counter += 1
            dict_switches_name["Switch{0}".format(counter)] = str(item["name"])
            dict_switches_id["Switch{0}".format(counter)] = str(item["id"])
        bot.sendMessage(
            chat_id,
            for_print,
            reply_markup=ReplyKeyboardMarkup(keyboard=[
                [
                    KeyboardButton(
                        text=str("Toggle " +
                                 dict_switches_name.get("Switch1"))),
                    KeyboardButton(text=str("Toggle " +
                                            dict_switches_name.get("Switch2")))
                ],
                [
                    KeyboardButton(
                        text=str("Toggle " +
                                 dict_switches_name.get("Switch3"))),
                    KeyboardButton(text=str("Toggle " +
                                            dict_switches_name.get("Switch4")))
                ],
                [KeyboardButton(text="Update information about switches")],
                [KeyboardButton(text="Return to Main Menu")],
            ]))


#Toggle switches
    elif command == str("Toggle " + dict_switches_name.get("Switch1")):
        requests.post(url=str("http://localhost:8090/api/switch/toggle/" +
                              dict_switches_id.get("Switch1")),
                      auth=(login_user_Terrarium_Pi,
                            login_password_Terrarium_Pi))
        for_print = requests.get(
            url=
            'http://localhost:8090/api/switches/dict_switches_id.get("Switch1")'
        ).json()["switches"][0]["state"]
        print(for_print)
        bot.sendMessage(chat_id, for_print)

    elif command == str("Toggle " + dict_switches_name.get("Switch2")):
        requests.post(url=str("http://localhost:8090/api/switch/toggle/" +
                              dict_switches_id.get("Switch2")),
                      auth=(login_user_Terrarium_Pi,
                            login_password_Terrarium_Pi))
        for_print = requests.get(
            url=
            'http://localhost:8090/api/switches/dict_switches_id.get("Switch2")'
        ).json()["switches"][0]["state"]
        print(for_print)
        bot.sendMessage(chat_id, for_print)

    elif command == str("Toggle " + dict_switches_name.get("Switch3")):
        requests.post(url=str("http://localhost:8090/api/switch/toggle/" +
                              dict_switches_id.get("Switch3")),
                      auth=(login_user_Terrarium_Pi,
                            login_password_Terrarium_Pi))
        for_print = requests.get(
            url=
            'http://localhost:8090/api/switches/dict_switches_id.get("Switch3")'
        ).json()["switches"][0]["state"]
        print(for_print)
        bot.sendMessage(chat_id, for_print)

    elif command == str("Toggle " + dict_switches_name.get("Switch4")):
        requests.post(url=str("http://localhost:8090/api/switch/toggle/" +
                              dict_switches_id.get("Switch4")),
                      auth=(login_user_Terrarium_Pi,
                            login_password_Terrarium_Pi))
        for_print = requests.get(
            url=
            'http://localhost:8090/api/switches/dict_switches_id.get("Switch4")'
        ).json()["switches"][0]["state"]
        print(for_print)
        bot.sendMessage(chat_id, for_print)

    elif command == "Administration":  #Menu - "Administration"
        bot.sendMessage(
            chat_id,
            "In this menu you can add or remove users who can chat with bot \nUNDER CONSTRUCTION",
            reply_markup=ReplyKeyboardMarkup(keyboard=[
                [KeyboardButton(text="Add/Remove user")],
                [KeyboardButton(text="Return to Main Menu")],
            ]))

    elif command == "Other tools":  #Menu - "Other tools"
        bot.sendMessage(
            chat_id,
            "Some features for yourself\nUNDER CONSTRUCTION",
            reply_markup=ReplyKeyboardMarkup(keyboard=[
                [
                    KeyboardButton(text="/time"),
                    KeyboardButton(text="/calendar")
                ],
                [KeyboardButton(text="/status"),
                 KeyboardButton(text="???")],
                [KeyboardButton(text="Return to Main Menu")],
            ]))
Exemple #7
0
def send_options(self, chat_id):

    entries = [["Film", "SerieTV"], ["Ricerca Regista, Film, SerieTV"]]
    markup = ReplyKeyboardMarkup(keyboard=entries)
    bot.sendMessage(chat_id, 'Scegli l\'opzione', reply_markup=markup)
    self.USER_STATE[chat_id] = 1
Exemple #8
0
def _rate_keyboard1():
    rate = list(map(lambda text: KeyboardButton(text=text), rate_text1))
    btn_lst = [[rate[0]], [rate[1]]]
    return ReplyKeyboardMarkup(keyboard=btn_lst)
Exemple #9
0
def _sponsor_default_keyboard():
    spon_temp = list(
        map(lambda text: KeyboardButton(text=text), sponsor_buttons_texts))
    btn_lst = [[spon_temp[0]], [spon_temp[1]], [spon_temp[2]]]
    return ReplyKeyboardMarkup(keyboard=btn_lst)
Exemple #10
0
def _location_default_keyboard():
    loc_temp = list(
        map(lambda text: KeyboardButton(text=text), locations_buttons_texts))
    btn_lst = [[loc_temp[0]], [loc_temp[2], loc_temp[3]], [loc_temp[4]]]
    return ReplyKeyboardMarkup(keyboard=btn_lst)
Exemple #11
0
def _poll_second_afternoon_keyboard():
    poll = list(map(lambda text: KeyboardButton(text=text), poll_texts))
    btn_lst = [[poll[3]], [poll[4]]]
    return ReplyKeyboardMarkup(keyboard=btn_lst)
Exemple #12
0
def _read_keyboard():
    read = list(map(lambda text: KeyboardButton(text=text), read_text))
    btn_lst = [[read[0]]]
    return ReplyKeyboardMarkup(keyboard=btn_lst)
Exemple #13
0
    def on_chat_message(self, msg):

        #command for entering name
        self.useless = msg[
            'text']  #to initiate chat ,user enters any key,which is not stored and whicch doesnt have any use on the program.Hence the first message is useless
        content_type, chat_type, chat_id = telepot.glance(msg)

        if self.count == 0 or msg['text'] == "/start":
            self.count = 0
            bot.sendMessage(
                chat_id,
                emojize("Hola Amigos!!! :smile: :snowman:", use_aliases=True))
            bot.sendMessage(chat_id, "I am Sparta")
            self.sender.sendMessage(
                emojize("Sparta the Bot :hatched_chick:", use_aliases=True))
            self.sender.sendMessage(
                emojize(
                    "Or to be more precise- I am the bot that makes teams for you!!! Great ain't it? :robot_face:",
                    use_aliases=True))
            Keyboard10 = ReplyKeyboardMarkup(
                one_time_keyboard=True,
                keyboard=[[KeyboardButton(text="Sure")]])
            self.sender.sendMessage(
                emojize(
                    "So... why don't we get started? :face_with_stuck-out_tongue: :ghost:",
                    use_aliases=True))
            self.sender.sendMessage("Press Sure to continue!!",
                                    reply_markup=Keyboard10)
            self.count += 1

        elif self.count == 1 or msg['text'] == '/main':
            self.count = 1
            self.useless2 = msg['text']

            self.sender.sendMessage(
                emojize(
                    "OKAY! So what do you want to do? :woman_dancing: Start your own game where players can join you or join someone else's team? :relaxed:",
                    use_aliases=True))
            Keyboard_categories5 = ('I wanna build my own team for a game!!!',
                                    'I wanna join a team!')
            Keyboard5 = ReplyKeyboardMarkup(
                one_time_keyboard=True,
                keyboard=[[KeyboardButton(text=x)]
                          for x in Keyboard_categories5])
            self.sender.sendMessage(
                emojize("*It's Play Time!!!* :baby_angel: :yum:",
                        use_aliases=True))
            self.sender.sendMessage("Okay so let's choose: ",
                                    reply_markup=Keyboard5)
            self.count += 1

        elif self.count == 2:
            self.choice1 = msg['text']
            if self.choice1 == "I wanna join a team!":
                self.sender.sendMessage(
                    emojize(
                        "Let's start by knowing your name?\nSo what do I call you? :cowboy_hat_face: :blue_heart:",
                        use_aliases=True))
                self.a = 1
                self.count += 1

            elif self.choice1 == "I wanna build my own team for a game!!!":
                self.sender.sendMessage(
                    emojize(
                        "Let's start by knowing your name?\nSo what do I call you? :cowboy_hat_face: :blue_heart:",
                        use_aliases=True))
                self.a = 0
                self.count += 1
            else:
                self.sender.sendMessage(
                    emojize(
                        "The input you entered was wrong.:sweat_drops:\nDont worry you still get to correct yourself :shit: :shit:\nEnter again-",
                        use_aliases=True))
                self.count = 2

        elif self.count == 3:
            if self.choice1 == "I wanna join a team!":
                FindersKeepers.name_joinTeam = msg['text']
                self.sender.sendMessage(
                    emojize(
                        "Heya " + FindersKeepers.name_joinTeam +
                        " Hope you are gonna really enjoy this experience! :smiling_face_with_halo:",
                        use_aliases=True))
            elif self.choice1 == "I wanna build my own team for a game!!!":
                FindersKeepers.name_buildTeam = msg['text']
                self.sender.sendMessage(
                    emojize(
                        "Heya " + FindersKeepers.name_buildTeam +
                        " Hope you are gonna really enjoy this experience! :smiling_face_with_halo:",
                        use_aliases=True))
            self.sender.sendMessage(
                emojize("Also carefully enter your matriculation number",
                        use_aliases=True))
            self.count += 1

        elif self.count == 4:

            if (self.string_length(msg['text']) == 9) and (msg['text'][:1]
                                                           == "U"):
                if self.choice1 == "I wanna join a team!":
                    FindersKeepers.matric_joinTeam = msg['text']

                elif self.choice1 == "I wanna build my own team for a game!!!":
                    FindersKeepers.matric_buildTeam = msg['text']

                Keyboard_categories1 = ('Indoor Games', 'Outdoor Games',
                                        'Video Games')
                Keyboard1 = ReplyKeyboardMarkup(
                    one_time_keyboard=True,
                    keyboard=[[KeyboardButton(text=x)]
                              for x in Keyboard_categories1])
                if self.a:
                    self.sender.sendMessage(emojize(
                        "Alrighty, you wanna join a team :star2: \nSet back and prepare yourself for the ride while we look for a team for you :notes: \nCould you please describe what  games you are interested in? :raised_hands:",
                        use_aliases=True),
                                            reply_markup=Keyboard1)
                    self.count = 5
                else:
                    self.sender.sendMessage(emojize(
                        "Yeyyy are you ready? :sparkles: Let's help you build a team :man_dancing:\nOkay! *Excited?* Let's start by which game you would like to play? :fire:",
                        use_aliases=True),
                                            reply_markup=Keyboard1)
                    self.count = 5
            else:
                self.sender.sendMessage(
                    "Carefully enter the matruiculation number AGAIN")
                self.count = 4

        elif self.count == 5:
            self.game_choice1 = msg['text']

            if self.game_choice1 == "Indoor Games":
                Keyboard_categories_indoor = ('Table Tennis', 'Gym',
                                              'Scrabble', 'Chess',
                                              'Game of Life', 'Ludo',
                                              'Heads up Charades', 'Carrom',
                                              'Chinese chess',
                                              'Other Indoor Games')
                Keyboard2 = ReplyKeyboardMarkup(
                    one_time_keyboard=True,
                    keyboard=[[KeyboardButton(text=event_category)]
                              for event_category in Keyboard_categories_indoor
                              ])
                self.sender.sendMessage("Okie dokie, let's get deeper -",
                                        reply_markup=Keyboard2)
                FindersKeepers.bd_game_check = msg['text']
                self.count = 6

            elif (self.game_choice1 == "Outdoor Games"):
                Keyboard_categories_outdoor = ('Badminton', 'Lawn Tennis',
                                               'Soccer', 'Squash', 'Swimming',
                                               'Basketball')
                Keyboard3 = ReplyKeyboardMarkup(
                    one_time_keyboard=True,
                    keyboard=[[KeyboardButton(text=event_category)]
                              for event_category in Keyboard_categories_outdoor
                              ])
                self.sender.sendMessage(emojize(
                    "Okie dokie, let's get deeper :dancers: :information_desk_person:",
                    use_aliases=True),
                                        reply_markup=Keyboard3)

                FindersKeepers.bd_game_check = msg['text']
                self.count = 6

            elif (self.game_choice1 == "Video Games"):
                Keyboard_categories_video = ('WWE', 'Fifa',
                                             'World of Warcraft',
                                             'Grand Theft Auto V',
                                             'Resident Evil 4', 'Call of Duty',
                                             'Other Video Games')
                Keyboard4 = ReplyKeyboardMarkup(
                    one_time_keyboard=True,
                    keyboard=[[KeyboardButton(text=event_category)]
                              for event_category in Keyboard_categories_video])
                self.sender.sendMessage(emojize(
                    "Okie dokie, let's get deeper :dancers: :information_desk_person:",
                    use_aliases=True),
                                        reply_markup=Keyboard4)

                FindersKeepers.bd_game_check = msg['text']
                self.count = 6

            else:
                self.sender.sendMessage(
                    emojize(
                        "The input you entered was wrong. :sweat_drops:\nDont worry you still get to correct yourself :shit: :shit: \nEnter again-",
                        use_aliases=True))
                self.count = 5

        elif (self.count == 6):
            FindersKeepers.bd_game_check = msg['text']
            if self.choice1 == "I wanna build my own team for a game!!!":
                if msg['text'] in FindersKeepers.video_games:
                    keyboard6 = ReplyKeyboardMarkup(
                        one_time_keyboard=True,
                        keyboard=[[KeyboardButton(text=x)]
                                  for x in FindersKeepers.videogames_place])
                    self.sender.sendMessage(
                        "So where exactly do you wanna play?",
                        reply_markup=keyboard6)
                    self.count += 1
                elif msg['text'] in FindersKeepers.indoor_games:
                    if msg['text'] == "Gym":
                        keyboard6 = ReplyKeyboardMarkup(
                            one_time_keyboard=True,
                            keyboard=[[KeyboardButton(text=x)]
                                      for x in FindersKeepers.gym_places])
                        self.sender.sendMessage(
                            "So where exactly do you wanna play?",
                            reply_markup=keyboard6)
                        self.count += 3
                    elif msg['text'] == "Table Tennis":
                        keyboard6 = ReplyKeyboardMarkup(
                            one_time_keyboard=True,
                            keyboard=[[KeyboardButton(text=x)]
                                      for x in FindersKeepers.tableTennis_court
                                      ])
                        self.sender.sendMessage(
                            "So where exactly do you wanna play?",
                            reply_markup=keyboard6)
                        self.count += 3
                    else:
                        keyboard6 = ReplyKeyboardMarkup(
                            one_time_keyboard=True,
                            keyboard=[[
                                KeyboardButton(text=x)
                            ] for x in FindersKeepers.other_indoor_places])
                        self.sender.sendMessage(
                            "So where exactly do you wanna play?",
                            reply_markup=keyboard6)
                        self.count += 1
                elif msg['text'] in FindersKeepers.outdoor_games:
                    for i in range(len(FindersKeepers.outdoor_games)):
                        if msg['text'] == FindersKeepers.outdoor_games[i]:
                            keyboard6 = ReplyKeyboardMarkup(
                                one_time_keyboard=True,
                                keyboard=[[
                                    KeyboardButton(text=x)
                                ] for x in FindersKeepers.outdoor_games_loc[i]
                                          ])
                            self.sender.sendMessage(
                                "So where exactly do you wanna play?",
                                reply_markup=keyboard6)
                            self.count += 3
                else:
                    self.count = 6
                    self.sender.sendMessage("Use custom keyboard pleasee")
            else:

                self.count += 13
                self.sender.sendMessage(
                    emojize(
                        "Cool! Wouldn't it be convenient if the players who want to join could contact you? :mailbox_with_mail: \nHelp us help you by sending us your contact! :hearts:",
                        use_aliases=True))

        elif (self.count == 7):
            FindersKeepers.bd_location_check = msg['text']
            if msg['text'] == "Halls" or msg[
                    'text'] in FindersKeepers.other_indoor_places:
                keyboard7 = ReplyKeyboardMarkup(
                    one_time_keyboard=True,
                    keyboard=[[KeyboardButton(text=x)]
                              for x in FindersKeepers.halls])
                self.sender.sendMessage(emojize(
                    "Let's be more specific :construction_worker:",
                    use_aliases=True),
                                        reply_markup=keyboard7)
                self.count += 1

        elif (self.count == 8):
            FindersKeepers.bd_location_check = FindersKeepers.bd_location_check + ": " + msg[
                'text']

            for i in range(len(FindersKeepers.halls)):
                if msg['text'] == FindersKeepers.halls[i]:
                    keyboard8 = ReplyKeyboardMarkup(
                        one_time_keyboard=True,
                        keyboard=[[KeyboardButton(text=x)]
                                  for x in FindersKeepers.halls_list[i]])
                    self.sender.sendMessage("Okay where exactly?",
                                            reply_markup=keyboard8)
                    self.count += 1

        elif (self.count == 9):
            if msg['text'] in FindersKeepers.all_halls:
                FindersKeepers.bd_location_check = FindersKeepers.bd_location_check + " :" + msg[
                    'text']
            else:
                FindersKeepers.bd_location_check = msg['text']
            option = ('Yes', 'Nope..next month please')
            keyboard5 = ReplyKeyboardMarkup(one_time_keyboard=True,
                                            keyboard=[[KeyboardButton(text=x)]
                                                      for x in option])
            self.sender.sendMessage(emojize(
                "Okay! So do you want to make a booking for this month? :smiling_face_with_smiling_eyes:",
                use_aliases=True),
                                    reply_markup=keyboard5)
            self.count += 1

        elif (self.count == 10):
            self.month_choice = msg["text"]
            if self.month_choice == "Yes":
                date = datetime.date.today()
                month_calendar = calendar.month(date.year, date.month)
                self.next_month = 0

            else:
                date = datetime.date.today()
                month_calendar = calendar.month(date.year, date.month + 1)
                self.next_month = 1
            self.sender.sendMessage(
                month_calendar +
                "\n\nCarefully now enter a suitable date for the month to build a team for that day!\nJust Enter a 2 digit number. Example: 02: "
            )
            self.count += 1

        elif (self.count == 11):
            self.date = msg['text']
            date = datetime.date.today()
            if (date.day <= int(self.date) <= 31 and self.next_month == 0):
                FindersKeepers.booking_date = self.date + "/" + str(
                    date.month) + "/" + str(date.year)
                self.sender.sendMessage(
                    emojize(
                        "Let's choose an appropriate time? :snowflake:\nYou are just a few steps away from your TEAM! :zap:\nType the time in this format please!\nabcd-wxyz...for example: 0930-1130 (in 24 hour format)",
                        use_aliases=True))
                self.count += 1
            elif (int(self.date) <= 31 and self.next_month == 1):
                FindersKeepers.booking_date = self.date + "/" + str(
                    date.month + 1) + "/" + str(date.year)
                self.sender.sendMessage(
                    emojize(
                        "Let's choose an appropriate time? :snowflake:\nYou are just a few steps away from your TEAM! :zap:\nType the time in this format please!\nabcd-wxyz...for example: 0930-1130 (in 24 hour format)",
                        use_aliases=True))
                self.count += 1
            else:
                self.sender.sendMessage("Inappropriate date...Enter again!")
                self.count = 11

        elif (self.count == 12):
            FindersKeepers.booking_time = msg['text']
            self.sender.sendMessage(
                emojize(
                    "Amazing we are done! You will be notified when players would want to join you! Congrats!! :hugging_face:",
                    use_aliases=True))
            keyboard11 = ReplyKeyboardMarkup(
                one_time_keyboard=True,
                keyboard=[[KeyboardButton(text="Sure!")]])
            self.sender.sendMessage("Press sure to continue!",
                                    reply_markup=keyboard11)
            self.count += 1

        elif (self.count == 13):
            self.useless3 = msg['text']
            #buttons = [[{"text": "Send", "request_contact": True}]]
            #keyboard_contact = {"keyboard": buttons, "one_time_keyboard": False, "resize_keyboard": True}
            self.sender.sendMessage(
                emojize(
                    "Cool! Wouldn't it be convenient if the players who want to join could contact you? :mailbox_with_mail: \nHelp us help you by sending us your contact! :hearts:",
                    use_aliases=True))
            self.count += 1

        elif (self.count == 14):
            FindersKeepers.contact_buildTeam = msg['text']
            self.sender.sendMessage(
                emojize(
                    "It would be really great if you could pass us your NTU email id so that we can inform whenever someone wanna join your team :mahjong: :smiley:",
                    use_aliases=True))
            self.count += 1

        elif (self.count == 15):
            FindersKeepers.email_buildTeam = msg['text']
            if ("@e.ntu.edu.sg" not in msg['text']):
                self.sender.sendMessage(
                    "Please input the CORRECT email id again!!!")
                self.count = 15
            else:
                self.sender.sendMessage(
                    "Umm...what is the minimum players you are looking for?")
                self.count += 1

        elif (self.count == 16):
            FindersKeepers.pmin_buildTeam = msg['text']
            self.sender.sendMessage("Ohkay...so what about maximum?")
            self.count += 1

        elif (self.count == 17):
            FindersKeepers.pmax_buildTeam = msg['text']
            self.sender.sendMessage("Alright then I guess we are done here")
            self.sender.sendMessage(
                emojize(
                    "As I said easy peasy lemon squeezy :lemon: ....We guys will inform you with the updates! :stuck_out_tongue_closed_eyes:",
                    use_aliases=True))
            keyboard8 = ReplyKeyboardMarkup(
                one_time_keyboard=True,
                keyboard=[[
                    KeyboardButton(text="Notify me when players found!")
                ]])
            self.sender.sendMessage(
                emojize("Well " + FindersKeepers.name_buildTeam +
                        "! Thanks a ton for your cooperation! :muscle:",
                        use_aliases=True),
                reply_markup=keyboard8)
            self.count += 1

        elif (self.count == 18):
            self.sender.sendMessage("Sure!")
            self.sender.sendMessage(
                emojize(
                    "You will be notified once the minimum number of players have joined your team :information_desk_person:",
                    use_aliases=True))
            self.sender.sendMessage(
                emojize(
                    "To make it convenient, the team will only be visible if the number of players is lesser than the maximum. :smile_cat: :dog:",
                    use_aliases=True))
            self.sender.sendMessage("Press /main to explore more!")
            FindersKeepers.lid = FindersKeepers.lid + 1
            self.add_data_TeamSetup(
                FindersKeepers.lid, chat_id, FindersKeepers.matric_buildTeam,
                FindersKeepers.email_buildTeam,
                FindersKeepers.contact_buildTeam,
                FindersKeepers.name_buildTeam, FindersKeepers.bd_game_check,
                FindersKeepers.booking_date, FindersKeepers.bd_location_check,
                FindersKeepers.booking_time, FindersKeepers.pmin_buildTeam,
                FindersKeepers.pmax_buildTeam)

        elif (self.count == 19):
            FindersKeepers.contact_joinTeam = msg['text']
            self.sender.sendMessage(
                emojize(
                    "Okay so here is a list of all those players looking for players to build their team in the near future! :dolphin:",
                    use_aliases=True))
            self.sender.sendMessage(
                "Just Enter one of the serial number to contact the person building teams and he will be notified via e-mail!!"
            )
            self.look_for_game_teamsetup(chat_id, FindersKeepers.bd_game_check)
            self.sender.sendMessage(
                "If no record found just press /main to explore more options!!"
            )
            self.count += 1

        elif (self.count == 20):
            FindersKeepers.sChosen_JD = int(msg['text'])

            con3 = lite.connect(
                "FionDB_sublime.db"
            )  #Gets data from team setup DB and uses it to add some of the data to the waitlist player DB
            cur3 = con3.cursor()
            cur3.execute(
                "SELECT Owner, Name, DateGame, TimeGame, Venue, MatriculationNumber, SerialNumber, OrganiserEmail, OrganiserContactNumber FROM TeamSetup WHERE SerialNumber=:SerialNumber",
                {"SerialNumber": int(msg['text'])})
            con3.commit()
            while True:
                self.rows = cur3.fetchone()
                if self.rows == None:
                    break
                FindersKeepers.sn = FindersKeepers.sn + 1  #keeps track of the serial number of the team setup DB
                self.addData_WaitlistPlayers(
                    FindersKeepers.sn, chat_id, FindersKeepers.matric_joinTeam,
                    FindersKeepers.contact_joinTeam,
                    FindersKeepers.name_joinTeam, FindersKeepers.bd_game_check,
                    FindersKeepers.sChosen_JD, self.rows[1], self.rows[2],
                    self.rows[3], self.rows[4], self.rows[0], self.rows[5],
                    self.rows[6], self.rows[7], self.rows[8])
                FindersKeepers.captured_sn_joinTeam = FindersKeepers.sn  #to know where the waitlisted player is added in the waitlist players DB

            self.sender.sendMessage(
                emojize("Wanna notify the team in charge? :eyes:",
                        use_aliases=True))
            keyboard9 = ReplyKeyboardMarkup(
                one_time_keyboard=True,
                keyboard=[[KeyboardButton(text="Sure!")]])
            self.sender.sendMessage("Press sure to continue!",
                                    reply_markup=keyboard9)
            self.count += 1

        elif (self.count == 21):
            con4 = lite.connect("FionDB_sublime.db")
            with con4:
                cur4 = con4.cursor()
                cur4.execute(
                    "SELECT Owner, SerialNumber, Name, PlayerContactNumber, MatriculationNumber, ChatIDPlayerContacted, MatricNumberPlayerContacted, SerialNumberPlayerContacted, EmailPlayerContacted, PhoneNumberPlayerContacted FROM WaitlistPlayers WHERE SerialNumber=:SerialNumber",
                    {"SerialNumber": FindersKeepers.captured_sn_joinTeam})
                con4.commit()
                self.rows = cur4.fetchone()
                if self.rows == None:
                    self.count = 1

                if self.rows[4] != self.rows[6]:
                    self.send_notification_email(self.rows[8])
                    self.tstrength_update_TeamSetup(self.rows[0], self.rows[7],
                                                    self.rows[5])
                    self.team_update_TeamSetup(self.rows[7], self.rows[5])
                    bot.sendMessage(
                        self.rows[5],
                        emojize(
                            "Congrats dude :smiling_face_with_sunglasses: ...\nThis player has joined your team!",
                            use_aliases=True))
                    bot.sendMessage(
                        self.rows[5],
                        emojize((
                            "%s %s %s %s" %
                            ("Serial Number: " + str(self.rows[1]),
                             "\nName: " + str(self.rows[2]),
                             "\nContact Number: " + str(self.rows[3]),
                             "\nMatriculation Number: " + str(self.rows[4])))))
                    bot.sendMessage(self.rows[5],
                                    "Press /main to explore more!")

                elif self.rows[4] == self.rows[
                        6]:  #Checks if both the matric numbers of the player in charge and the player making the request is the same so that the player does not accidentally add into his own team
                    bot.sendMessage(
                        self.rows[0],
                        emojize(
                            "Well...Don't joke...you cant join your own team! \nAnd matric number is unique for every individual! :unamused_face:",
                            use_aliases=True))
                    bot.sendMessage(
                        self.rows[0],
                        "Invalid Request...Press /main to restart!")
                    bot.sendMessage(self.rows[0],
                                    "Press /main to explore more!")

                elif self.rows == None:
                    bot.sendMessage(chat_id, "No records found")
                    bot.sendMessage(self.rows[0],
                                    "Press /main to explore more!")

            self.count = 1
Exemple #14
0
def on_chat_message(msg):
    content_type, chat_type, chat_id = telepot.glance(
        msg)  # inizializzazione delle variabili
    name = msg["from"]["first_name"]
    if content_type == 'text':
        comando = msg['text']

        # pulsantiera principale
        if (comando == '/start') or (comando == '/home'):
            bot.sendMessage(chat_id,
                            text="Ciao %s! " % name + select + '\n' +
                            info + gruppi + contatti + risorse + orario,
                            reply_markup=ReplyKeyboardMarkup(
                                keyboard=[[KeyboardButton(text='/info'),
                                           KeyboardButton(text='/gruppi')],
                                          [KeyboardButton(text='/contatti'),
                                           KeyboardButton(text='/risorse')],
                                          [KeyboardButton(text='/orario')]]))

        # info del fiup
        if (comando == '/info'):
            bot.sendMessage(chat_id,
                            text=abstract + '\n' + scopo + '\n' +
                            rules + '\n\n' + home,
                            parse_mode='markdown')

        # Avvia la pulsantiera relativa ai gruppi
        if (comando == '/gruppi'):
            bot.sendMessage(chat_id,
                            primo + secondo + terzo + opzionali + altro,
                            parse_mode='markdown',
                            reply_markup=ReplyKeyboardMarkup(
                                keyboard=[[KeyboardButton(text='/primo'),
                                           KeyboardButton(text='/secondo')],
                                          [KeyboardButton(text='/terzo'),
                                           KeyboardButton(text='/opzionali')],
                                          [KeyboardButton(text='/altro'),
                                           KeyboardButton(text='/home')]]))

        if (comando == '/primo'):
            bot.sendMessage(chat_id, infoPrimo,
                            parse_mode='markdown',
                            disable_web_page_preview=True)
        if (comando == '/secondo'):
            bot.sendMessage(chat_id, infoSec,
                            parse_mode='markdown',
                            disable_web_page_preview=True)
        if (comando == '/terzo'):
            bot.sendMessage(chat_id, infoTer,
                            parse_mode='markdown',
                            disable_web_page_preview=True)
        if (comando == '/opzionali'):
            bot.sendMessage(chat_id, infoOpz,
                            parse_mode='markdown',
                            disable_web_page_preview=True)
        if (comando == '/altro'):
            bot.sendMessage(chat_id, infoAltro,
                            parse_mode='markdown',
                            disable_web_page_preview=True)

        # Avvia la pulsantiera del regolamento
        if comando == '/contatti':
            bot.sendMessage(chat_id,
                            contatti + '\n' + infoContatti + '\n' + social,
                            parse_mode='markdown',
                            disable_web_page_preview=True)

            # bot.sendMessage(chat_id, text = text="*bold* _italic_
            # `fixed width font` [link](http).", parse_mode = 'markdown')

        # Avvia la pulsantiera delle risorse
        if comando == '/risorse':
            bot.sendMessage(chat_id,
                            text=risorse + '\n' + mega + github + stampe,
                            parse_mode='markdown',
                            disable_web_page_preview=True)

        if comando == "/orario":
            bot.sendMessage(chat_id,
                            text=appDM + booking + aule,
                            parse_mode='markdown',
                            disable_web_page_preview=True)
Exemple #15
0
    ordersfile = open('orders.txt', 'w')
    db.execute('SELECT * FROM Orders')
    row = db.fetchall()
    for tupl in row:
        string = '==================================='
        string += '\nNo.' + str(tupl[0]) + '\nPhone number: ' + str(
            tupl[1]) + '\nName: ' + str(tupl[2]) + '\nDestination: ' + str(
                tupl[3])
        string += '\nMenu: ' + str(tupl[4]) + '\nCost: ' + str(tupl[5]) + '\n'
        ordersfile.write(string)
    ordersfile.close()


remove_markup = ReplyKeyboardRemove()
markup_main_menu = ReplyKeyboardMarkup(keyboard=[[
    KeyboardButton(text='Add order')
], [KeyboardButton(text="View orders"),
    KeyboardButton(text="Don't touch!")], [KeyboardButton(text='Quit')]])
inline_yes_no = InlineKeyboardMarkup(inline_keyboard=[
    [
        InlineKeyboardButton(text='Yes', callback_data='yes'),
        InlineKeyboardButton(text='No', callback_data='no')
    ],
])
inline_chose_data = InlineKeyboardMarkup(inline_keyboard=[
    [
        InlineKeyboardButton(text='Phone number', callback_data='number'),
        InlineKeyboardButton(text='Name', callback_data='name')
    ],
    [
        InlineKeyboardButton(text='Destination', callback_data='destination'),
        InlineKeyboardButton(text='Menu', callback_data='menu')
Exemple #16
0
def _contact_us_keyboard1():
    contactUs_temp = list(
        map(lambda text: KeyboardButton(text=text), contact_us_buttons_text1))
    btn_lst = [[contactUs_temp[0]]]
    return ReplyKeyboardMarkup(keyboard=btn_lst)
Exemple #17
0
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()
    user_message = msg['text'].lower()
    if user_message =='/start':   
    p = FlagTs(user_message)
    bot.sendMessage(chat_id,f'{user_message}')
    if command == '/start':
        markup = ReplyKeyboardMarkup(keyboard=[['🇿🇦', KeyboardButton(text='🇦🇱'), KeyboardButton(text='🇽🇰'), KeyboardButton(text='🇲🇪'), KeyboardButton(text='🇪🇷')], [
            dict(text='🇪🇹'), KeyboardButton(text='🇩🇿'), KeyboardButton(text='🇧🇭'), KeyboardButton(text='🇹🇩'), KeyboardButton(text='🇰🇲')], [
                                     dict(text='🇩🇯'), KeyboardButton(text='🇪🇬'), KeyboardButton(text='🇮🇶'), KeyboardButton(text='🇯🇴'), KeyboardButton(text='🇰🇼')], [
                                         dict(text='🇱🇧'), KeyboardButton(text='🇱🇾'), KeyboardButton(text='🇲🇷'), KeyboardButton(text='🇲🇦'), KeyboardButton(text='🇴🇲')], [
                                         dict(text='🇵🇸'), KeyboardButton(text='🇶🇦'), KeyboardButton(text='🇸🇦'), KeyboardButton(text='🇸🇴'), KeyboardButton(text='🇸🇩')], [
                                             dict(text='🇸🇾'), KeyboardButton(text='🇹🇳'), KeyboardButton(text='🇦🇪'), KeyboardButton(text='🇾🇪'), KeyboardButton(text='🇦🇲')], [
                                             dict(text='🇦🇿'), KeyboardButton(text='🇧🇩'), KeyboardButton(text='🇧🇦'), KeyboardButton(text='🇧🇬'), KeyboardButton(text='🇦🇩')], [
                                                 dict(text='🇲🇼'), KeyboardButton(text='🇨🇳'), KeyboardButton(text='🇹🇼'), KeyboardButton(text='🇭🇷'), KeyboardButton(text='🇧🇪')], [
                                                     dict(text='🇩🇰'), KeyboardButton(text='🇳🇱'), KeyboardButton(text='🇸🇷'), KeyboardButton(text='🇦🇬'), KeyboardButton(text='🇦🇺')], [
                                                         dict(text='🇧🇸'), KeyboardButton(text='🇧🇧'), KeyboardButton(text='🇧🇿'), KeyboardButton(text='🇧🇼'), KeyboardButton(text='🇨🇲')], [
                                                             dict(text='🇨🇦'), KeyboardButton(text='🇩🇲'), KeyboardButton(text='🇸🇿'), KeyboardButton(text='🇬🇲'), KeyboardButton(text='🇬🇭')], [
                                                                 dict(text='🇬🇩'), KeyboardButton(text='🇬🇾'), KeyboardButton(text='🇭🇰'), KeyboardButton(text='🇯🇲'), KeyboardButton(text='🇰🇪')],[
                                                                     dict(text='🇰🇮'), KeyboardButton(text='🇱🇸'), KeyboardButton(text='🇱🇷'), KeyboardButton(text='🇲🇭'), KeyboardButton(text='🇳🇦')],[
                                                                         dict(text='🇳🇷'), KeyboardButton(text='🇳🇬'), KeyboardButton(text='🇵🇼'), KeyboardButton(text='🇵🇬'), KeyboardButton(text='🇰🇳')],[
                                                                             dict(text='🇱🇨'), KeyboardButton(text='🇻🇨'), KeyboardButton(text='🇼🇸'), KeyboardButton(text='🇸🇨'), KeyboardButton(text='🇸🇱')],[
                                                                                 dict(text='🇸🇧'), KeyboardButton(text='🇸🇸'), KeyboardButton(text='🇹🇿'), KeyboardButton(text='🇹🇴'), KeyboardButton(text='🇹🇹')],[
                                                                                     dict(text='🇹🇻'), KeyboardButton(text='🇺🇬'), KeyboardButton(text='🇬🇧'), KeyboardButton(text='🇺🇸'), KeyboardButton(text='🇻🇺')],[
                                                                                         dict(text='🇿🇲'), KeyboardButton(text='🇿🇼'), KeyboardButton(text='🇪🇪'), KeyboardButton(text='🇵🇭'), KeyboardButton(text='🇫🇮')],[
                                                                                             dict(text='🇧🇯'), KeyboardButton(text='🇧🇫'), KeyboardButton(text='🇧🇮'), KeyboardButton(text='🇨🇫'), KeyboardButton(text='🇨🇩')],[
                                                                                                 dict(text='🇬🇶'), KeyboardButton(text='🇫🇷'), KeyboardButton(text='🇬🇦'), KeyboardButton(text='🇬🇳'), KeyboardButton(text='🇲🇱')],[
                                                                                                     dict(text='🇲🇨'), KeyboardButton(text='🇳🇪'), KeyboardButton(text='🇸🇳'), KeyboardButton(text='🇨🇭'), KeyboardButton(text='🇹🇬')],[
                                                                                                         dict(text='🇬🇪'), KeyboardButton(text='🇦🇹'), KeyboardButton(text='🇩🇪'), KeyboardButton(text='🇱🇮'), KeyboardButton(text='🇨🇾')],[
                                                                                                             dict(text='🇬🇷'), KeyboardButton(text='🇭🇹'), KeyboardButton(text='🇮🇱'), KeyboardButton(text='🇮🇳'), KeyboardButton(text='🇭🇺')],[
                                                                                                                 dict(text='🇮🇸'), KeyboardButton(text='🇮🇩'), KeyboardButton(text='🇮🇪'), KeyboardButton(text='🇮🇹'), KeyboardButton(text='🇸🇲')],[
                                                                                                                     dict(text='🇻🇦'), KeyboardButton(text='🇯🇵'), KeyboardButton(text='🇰🇿'), KeyboardButton(text='🇰🇵'), KeyboardButton(text='🇰🇷')],[
                                                                                                                         dict(text='🇽🇰'), KeyboardButton(text='🇱🇦'), KeyboardButton(text='🇱🇻'), KeyboardButton(text='🇱🇹'), KeyboardButton(text='🇱🇺')],[
                                                                                                                             dict(text='🇲🇬'), KeyboardButton(text='🇧🇳'), KeyboardButton(text='🇲🇾'), KeyboardButton(text='🇲🇹'), KeyboardButton(text='🇳🇿')],[
                                                                                                                                 dict(text='🇲🇳'), KeyboardButton(text='🇳🇵'), KeyboardButton(text='🇳🇴'), KeyboardButton(text='🇦🇫'), KeyboardButton(text='🇮🇷')],[
                                                                                                                                     dict(text='🇵🇱'), KeyboardButton(text='🇦🇴'), KeyboardButton(text='🇧🇷'), KeyboardButton(text='🇨🇻'), KeyboardButton(text='🇬🇼')],[
                                                                                                                                         dict(text='🇲🇴'), KeyboardButton(text='🇲🇿'), KeyboardButton(text='🇵🇹'), KeyboardButton(text='🇸🇹'), KeyboardButton(text='🇲🇩')],[
                                                                                                                                             dict(text='🇷🇴'), KeyboardButton(text='🇰🇬'), KeyboardButton(text='🇷🇺'), KeyboardButton(text='🇷🇸'), KeyboardButton(text='🇱🇰')],[
                                                                                                                                                 dict(text='🇨🇿'), KeyboardButton(text='🇸🇰'), KeyboardButton(text='🇸🇮'), KeyboardButton(text='🇦🇷'), KeyboardButton(text='🇨🇴')],[
                                                                                                                                                     dict(text='🇨🇷'), KeyboardButton(text='🇨🇺'), KeyboardButton(text='🇩🇴'), KeyboardButton(text='🇪🇨'), KeyboardButton(text='🇸🇻')],[
                                                                                                                                                         dict(text='🇬🇹'), KeyboardButton(text='🇭🇳'), KeyboardButton(text='🇲🇽'), KeyboardButton(text='🇳🇮'), KeyboardButton(text='🇵🇦')],[
                                                                                                                                                             dict(text='🇵🇾'), KeyboardButton(text='🇵🇪'), KeyboardButton(text='🇪🇸'), KeyboardButton(text='🇺🇾'), KeyboardButton(text='🇻🇪')],[
                                                                                                                                                                 dict(text='🇷🇼'), KeyboardButton(text='🇸🇪'), KeyboardButton(text='🇹🇯'), KeyboardButton(text='🇸🇬'), KeyboardButton(text='🇹🇭')],[
                                                                                                                                                                 dict(text='🇺🇦'), KeyboardButton(text='🇵🇰'), KeyboardButton(text='🇺🇿'), KeyboardButton(text='🇻🇳'),KeyboardButton(text='Back')], ], resize_keyboard=True)
        

        responce = bot.getChat(chat_id)
        first_name = responce['first_name']
        bot.sendMessage(chat_id, f'hello {first_name}', reply_markup=markup)


TOKEN = '1346878810:AAGj0p_Hoq1YZjm_K78YLTLc_7Q_NqkHbNo'
# your token
bot = telepot.Bot(TOKEN)
answerer = telepot.helper.Answerer(bot)

MessageLoop(bot, {'chat': on_chat_message}).run_as_thread()
print('Listening ...')

# Keep the program running.
while 1:
    time.sleep(10)
Exemple #18
0
def _day2_keyboard():
    day2 = list(map(lambda text: KeyboardButton(text=text),
                    day2_buttons_texts))
    btn_lst = [[day2[0]], [day2[1]], [day2[2]]]
    return ReplyKeyboardMarkup(keyboard=btn_lst)
Exemple #19
0
    def handle(self, msg):
        content_type, chat_type, chat_id = telepot.glance(msg)
        photos = []
        links = []
        titoli = []
        posizioni = []

        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text='Trama', callback_data='trama')],
        ])

        # Check user state
        try:
            self.USER_STATE[chat_id]
        except KeyError:
            self.USER_STATE[chat_id] = 0

        # se messaggio ricevuto è un testo
        if content_type == "text":

            input_msg = msg['text']

            if input_msg == "/start":
                # messaggio di benvenuto
                bot.sendMessage(
                    chat_id, "Benvenuto " + msg['chat']['first_name'] +
                    " questo bot ti aiuterà a scegliere il film che più è adatto a te"
                )
                send_options(self, chat_id)

            # Se è scritto HOME, messaggio di inizio.
            elif input_msg == "HOME" or input_msg == "/HOME":
                send_options(self, chat_id)

            # apre la schermata di ricerca di un film
            elif input_msg == "Ricerca Regista, Film, SerieTV" and self.USER_STATE[
                    chat_id] == 1:
                reply_markup = ReplyKeyboardRemove()
                bot.sendMessage(
                    chat_id,
                    'Digita il film che vuoi cercare...\nSe sai già il titolo... ',
                    reply_markup=reply_markup)
                self.USER_STATE[chat_id] = 3.1

            # e in caso di corrispondenza stampa la lista dei film
            elif self.USER_STATE[chat_id] == 3.1:
                r = requests.get("http://127.0.0.1:9544/{0}".format(
                    input_msg.replace(' ', '-')))
                myresult = r.json()
                links = myresult['links']
                stampa_lista_film(chat_id, links)

            # apre la schermata di ricerca delle serie tv
            elif input_msg == "SerieTV" and self.USER_STATE[chat_id] == 1:
                entries = [["Genere", "Piu Viste"], ["HOME"]]
                markup = ReplyKeyboardMarkup(keyboard=entries)
                bot.sendMessage(chat_id,
                                'Seleziona il filtraggio...',
                                reply_markup=markup)
                self.USER_STATE[chat_id] = 7

            # filtro delle serieTV in base al Genere
            elif input_msg == "Genere" and self.USER_STATE[chat_id] == 7:
                entries = [["Drama", "Science Fiction", "Fantasy"],
                           ["Crime", "Animation", "Comedy"], ["HOME"]]
                markup = ReplyKeyboardMarkup(keyboard=entries)
                bot.sendMessage(chat_id,
                                'Seleziona il filtraggio...',
                                reply_markup=markup)
                self.USER_STATE[chat_id] = 8

            # stampa le locandine delle varie serietv del genere selezionato
            elif self.USER_STATE[chat_id] == 8:
                r = requests.get(
                    "http://127.0.0.1:9544/tipologia/{0}/{1}".format(
                        self.USER_STATE[chat_id], input_msg.replace(' ', '-')))
                myresult = r.json()
                myresult = r.json()
                photos = myresult['photos']
                links = myresult['links']
                titoli = myresult['titoli']
                posizioni = myresult['posizioni']
                cerca_locandine(self, chat_id, photos, links, titoli,
                                posizioni, input_msg)

            # cerca e stampa le serieTV più Viste
            elif (input_msg == "Piu Viste" and self.USER_STATE[chat_id] == 7):
                r = requests.get(
                    "http://127.0.0.1:9544/tipologia/{0}/{1}".format(
                        self.USER_STATE[chat_id], input_msg.replace(' ', '-')))
                myresult = r.json()
                myresult = r.json()
                photos = myresult['photos']
                links = myresult['links']
                titoli = myresult['titoli']
                posizioni = myresult['posizioni']
                cerca_locandine(self, chat_id, photos, links, titoli,
                                posizioni, input_msg)

            # apre la schermata dei film con i vari modi di filtraggio delle ricerche
            elif input_msg == "Film" and self.USER_STATE[chat_id] == 1:
                entries = [["Genere", "Anno"], ["Nazione"], ["HOME"]]
                markup = ReplyKeyboardMarkup(keyboard=entries)
                bot.sendMessage(chat_id,
                                'Seleziona il filtraggio...',
                                reply_markup=markup)
                self.USER_STATE[chat_id] = 2

            # Filtro in base all'Anno
            elif input_msg == "Anno" and self.USER_STATE[chat_id] == 2:
                entries = [["2019"], ["2018"], ["2017"], ["2016"], ["HOME"]]
                markup = ReplyKeyboardMarkup(keyboard=entries)
                bot.sendMessage(chat_id,
                                'Seleziona l\'Anno',
                                reply_markup=markup)
                self.USER_STATE[chat_id] = 6

            # Restituisce i film dell'Anno selezionato
            elif self.USER_STATE[chat_id] == 6:
                r = requests.get(
                    "http://127.0.0.1:9544/tipologia/{0}/{1}".format(
                        self.USER_STATE[chat_id], input_msg.replace(' ', '-')))
                myresult = r.json()
                myresult = r.json()
                photos = myresult['photos']
                links = myresult['links']
                titoli = myresult['titoli']
                posizioni = myresult['posizioni']
                cerca_locandine(self, chat_id, photos, links, titoli,
                                posizioni, input_msg)

            # filtro dei film in base al Genere
            elif input_msg == "Genere" and self.USER_STATE[chat_id] == 2:
                entries = [["Drammatici", "Commedie", "Biografici"],
                           [
                               "Animazione cartoni animati", "Fantascienza",
                               "Horror"
                           ], ["Musical", "Documentari", "Supereroi"],
                           ["Western", "Guerra", "Thriller Suspence"],
                           ["Per tutta la famiglia"], ["HOME"]]
                markup = ReplyKeyboardMarkup(keyboard=entries)
                bot.sendMessage(chat_id,
                                'Scegli l\'opzione',
                                reply_markup=markup)
                self.USER_STATE[chat_id] = 5

            # filtro dei Film in base alla nazione
            elif input_msg == "Nazione" and self.USER_STATE[chat_id] == 2:
                entries = [[
                    "Italiani", "Giapponesi", "Cinesi Hong-kong Taiwan"
                ], ["Francesi", "Russi", "Australiani"], ["HOME"]]
                markup = ReplyKeyboardMarkup(keyboard=entries)
                bot.sendMessage(chat_id,
                                'Scegli l\'opzione',
                                reply_markup=markup)
                self.USER_STATE[chat_id] = 4

            # restitusce i film della nazione cercata
            elif self.USER_STATE[chat_id] == 4:
                r = requests.get(
                    "http://127.0.0.1:9544/tipologia/{0}/{1}".format(
                        self.USER_STATE[chat_id], input_msg.replace(' ', '-')))
                print(str(r))
                myresult = r.json()
                photos = myresult['photos']
                links = myresult['links']
                titoli = myresult['titoli']
                posizioni = myresult['posizioni']
                cerca_locandine(self, chat_id, photos, links, titoli,
                                posizioni, input_msg)

            # Restituisce i migliori film di ogni Genere
            elif self.USER_STATE[chat_id] == 5 and input_msg != "HOME":
                if input_msg == "Commedie":
                    entries = [["Le commedie piu belle"],
                               ["migliori commedie 2018"],
                               ["migliori commedie 2017"],
                               ["migliori commedie 2016"], ["HOME"]]
                    markup = ReplyKeyboardMarkup(keyboard=entries)
                    bot.sendMessage(chat_id,
                                    'Scegli l\'opzione',
                                    reply_markup=markup)
                    self.USER_STATE[chat_id] = 5.1

                else:
                    if input_msg == "Fantascienza":
                        input_msg = "fantascienza-sci-fi"
                    r = requests.get(
                        "http://127.0.0.1:9544/tipologia/{0}/{1}".format(
                            self.USER_STATE[chat_id],
                            input_msg.replace(' ', '-')))
                    myresult = r.json()
                    photos = myresult['photos']
                    links = myresult['links']
                    titoli = myresult['titoli']
                    posizioni = myresult['posizioni']
                    if (photos == []):
                        self.USER_STATE[chat_id] = 5.2
                        r = requests.get(
                            "http://127.0.0.1:9544/tipologia/{0}/{1}".format(
                                self.USER_STATE[chat_id],
                                input_msg.replace(' ', '-')))
                        myresult = r.json()
                        photos = myresult['photos']
                        links = myresult['links']
                        titoli = myresult['titoli']
                        posizioni = myresult['posizioni']
                    self.USER_STATE[chat_id] = 5

                    cerca_locandine(self, chat_id, photos, links, titoli,
                                    posizioni, input_msg)

            elif self.USER_STATE[chat_id] == 5.1:
                r = requests.get(
                    "http://127.0.0.1:9544/tipologia/{0}/{1}".format(
                        self.USER_STATE[chat_id], input_msg.replace(' ', '-')))
                myresult = r.json()
                photos = myresult['photos']
                links = myresult['links']
                titoli = myresult['titoli']
                posizioni = myresult['posizioni']
                cerca_locandine(self, chat_id, photos, links, titoli,
                                posizioni, input_msg)

            else:
                bot.sendMessage(chat_id, "Comando non trovato...")
Exemple #20
0
def _create_default_keyboard():
    # return ReplyKeyboardMarkup(keyboard=[KeyboardButton(text=keyboard_text) for keyboard_text in default_buttons_texts])
    temp = list(
        map(lambda text: KeyboardButton(text=text), default_buttons_texts))
    btn_lst = [[temp[0], temp[1], temp[2]], [temp[4], temp[5]]]
    return ReplyKeyboardMarkup(keyboard=btn_lst)
def handle(msg):
    content_type, chat_type, chat_id  = telepot.glance(msg)
    
    iPhone_names =[
        'iPhone 5s',
        'iPhone SE',
        'iPhone 6',
        'iPhone 6 Plus',
        'iPhone 6s',
        'iPhone 6s Plus',
        'iPhone 7',
        'iPhone 7 Plus',
        'iPhone 8',
        'iPhone 8 Plus',
        'iPhone X',
        'iPhone XS',
        'iPhone XS Max',
        'iPhone XR'
    ]
    
    # username = msg['from']['username']
    
    # user_id = msg['from']['id']
    
    if content_type == 'text':
        text = msg['text']


        if text == '/searchprices':
            menu= []
            index = 0
            line = []
            for  i in range(0,len(iPhone_names)): 
                if index < 1:
                    line.append(KeyboardButton(text = iPhone_names[i]))
                    index += 1
                elif index == 1:
                    index += 1
                    line.append(KeyboardButton(text = iPhone_names[i]))
                    menu.append(line)
                    index = 0
                    line = []


            bot.sendMessage(chat_id, 'Scegli un modello',
                            reply_markup=ReplyKeyboardMarkup(
                                keyboard=menu,
                                one_time_keyboard=True
                            ))


        if text== '/keepmeupdated':
            keyboard =  [[InlineKeyboardButton(text="Option 1")]]
                        
                

            bot.sendMessage(chat_id, 'Funzione in fase di sviluppo',
                            
                            reply_markup=InlineKeyboardMarkup(
                                InlineKeyboard=[[InlineKeyboardButton(text="ciao", callback_data='press')],
                                ])
                            )
                                              



        if text in iPhone_names :
            
            print("Cercato",text)

            with open('prices1.json', 'r') as input_file:
                j_data=json.load(input_file)
            with open('iPhone_type.json', 'r') as config_file:
                j_config=json.load(config_file)

            #dichiarazione variabili
            to_search=iPhone_names.index(text)
            right_search=list(j_config.keys())[to_search]
            reply_to_send=""
            global_title=[]
            global_price=[]
            global_link=[]
            indexes= sorted(range(len(global_price)), key=lambda k: global_price[k])
            
            #global_order={"Titles": [], "Links": [], "Prices": []} 


            for i in j_data:

                max=0
                for j in range(len(j_data[i][right_search])):
                    if max>=2:
                        break 
                    global_title.append(j_data[i][right_search][j][0])
                    global_link.append(j_data[i][right_search][j][1])
                    global_price.append(str(j_data[i][right_search][j][2]))
                    max+=1
            
            #Qui viene creata la Tupla contenente le varie liste
            global_order=list(map(lambda x, y,z:(x,y,z), global_title, global_price, global_link)) 

            #Qui viene ordinata la Tupla (Global order) contenente le liste
            size= lambda global_order:global_order[1]
            global_order.sort(key=size)
            print(global_title)


            # global_order["Titles"].append(global_title)
            # global_order["Links"].append(global_link)
            # global_order["Prices"].append(global_price)
            ########### Il problema è qui #############
           
            
           
            #Ordina per prezzo
            #sorted_global_order= sorted(global_order.items(), key=operator.itemgetter(1))
            #Non ordina in modo corretto, crea una lista noi vogliamo il dizionario forse
            
            
            
            

            for title,price,link in global_order: 
                title_to_send= (title)
                
                price_to_send= ("<b>"+str(price)+"€</b>")
                
                link_to_send=(link)
                
                reply_to_send+=("📱 "+title_to_send+ "\n"+ "💶 "+price_to_send+"   ")
                reply_to_send+=("<a href='"+link+"'>"+"Link"+"</a>"+"\n\n")
                reply_to_send+=("--------------------\n")



            bot.sendMessage(chat_id, reply_to_send,
                            disable_web_page_preview=True,
                            parse_mode='HTML',
                            reply_markup=ReplyKeyboardRemove()                            
                            )           
def initiate_bashnya():
    keyboard = ReplyKeyboardMarkup(
        keyboard=[[KeyboardButton(text="Где я могу найти их?")]])
    return keyboard
def start(msg):
    pprint(msg)
    content_type, chat_type, chat_id = telepot.glance(msg)
    try:
        languag[chat_id]
    except KeyError:
        try:
            languag[chat_id] = msg['from']['language_code']
        except KeyError:
            languag[chat_id] = "en"
    if check_flood(chat_id, languag[chat_id], msg) == "BANNED":
        return
    statisc(chat_id, "USERS")
    try:
        qualit[chat_id]
    except KeyError:
        qualit[chat_id] = "MP3_320"
    try:
        users[chat_id]
    except KeyError:
        users[chat_id] = 0
    if content_type == "text" and msg['text'] == "/start":
        try:
            sendPhoto(
                chat_id,
                open("example.png", "rb"),
                caption=translate(
                    languag[chat_id],
                    "Welcome to @DeezloaderRMX_bot\nThe bot commands can find here"
                ))
        except FileNotFoundError:
            pass
        sendMessage(
            chat_id,
            translate(
                languag[chat_id],
                "Press for search songs or albums or artists\nP.S. Remember you can do this digiting @ in your keyboard and select DeezloaderRMX_bot\nSend a Deezer or Spotify link to download\nSend a song o vocal message to recognize the track"
            ),
            reply_markup=InlineKeyboardMarkup(
                inline_keyboard=[[
                    InlineKeyboardButton(
                        text="Search artist",
                        switch_inline_query_current_chat="artist:"),
                    InlineKeyboardButton(
                        text="Search album",
                        switch_inline_query_current_chat="album:")
                ],
                                 [
                                     InlineKeyboardButton(
                                         text="Search global",
                                         switch_inline_query_current_chat="")
                                 ]]))
    elif content_type == "text" and msg['text'] == "/translator":
        if languag[chat_id] != "en":
            languag[chat_id] = "en"
            sendMessage(
                chat_id,
                translate(languag[chat_id],
                          "Now the language will be english"))
        else:
            languag[chat_id] = msg['from']['language_code']
            sendMessage(
                chat_id,
                translate(languag[chat_id],
                          "Now the bot will use the Telegram app language"))
    elif content_type == "text" and msg['text'] == "/quality":
        sendMessage(
            chat_id,
            translate(languag[chat_id],
                      "Choose the quality that you want to download the song"),
            reply_markup=ReplyKeyboardMarkup(
                keyboard=[[
                    KeyboardButton(text="FLAC"),
                    KeyboardButton(text="MP3_320Kbps")
                ],
                          [
                              KeyboardButton(text="MP3_256Kbps"),
                              KeyboardButton(text="MP3_128Kbps")
                          ]]))
    elif content_type == "text" and (msg['text'] == "FLAC"
                                     or msg['text'] == "MP3_320Kbps"
                                     or msg['text'] == "MP3_256Kbps"
                                     or msg['text'] == "MP3_128Kbps"):
        qualit[chat_id] = msg['text'].replace("Kbps", "")
        sendMessage(chat_id,
                    translate(
                        languag[chat_id],
                        "The songs will be downloaded with " + msg['text'] +
                        " quality"),
                    reply_markup=ReplyKeyboardRemove())
        sendMessage(
            chat_id,
            translate(
                languag[chat_id],
                "The songs that cannot be downloaded with the quality that you choose will be downloaded in the best quality possible"
            ))
    elif content_type == "voice" or content_type == "audio":
        Thread(target=Audio,
               args=(msg[content_type]['file_id'], chat_id,
                     languag[chat_id])).start()
    elif content_type == "text" and msg['text'] == "/info":
        sendMessage(
            chat_id,
            "Version: 1.1 RMX\nName:@DeezloaderRMX_bot\nCreator:@An0nimia\nDonation:https://www.paypal.me/An0nimia\nForum:https://t.me/DeezloaderRMX_group\nUsers:"
            + statisc(chat_id, "USERS") + "\nTracks downloaded:" +
            statisc(chat_id, "TRACKS"))
    elif content_type == "text":
        try:
            msg['entities']
            if ans == "2" and users[chat_id] == 3:
                sendMessage(
                    chat_id,
                    translate(
                        languag[chat_id],
                        "Wait to finish and resend the link, did you thought that you could download how much songs did you want? :)"
                    ))
            else:
                if ans == "2":
                    users[chat_id] += 1
                Thread(target=Link,
                       args=(msg['text'].replace("'", ""), chat_id,
                             languag[chat_id], qualit[chat_id], msg)).start()
        except KeyError:
            sendMessage(
                chat_id,
                translate(languag[chat_id], "Press"),
                reply_markup=InlineKeyboardMarkup(inline_keyboard=[
                    [
                        InlineKeyboardButton(
                            text="Search artist",
                            switch_inline_query_current_chat="artist:" +
                            msg['text']),
                        InlineKeyboardButton(
                            text="Search album",
                            switch_inline_query_current_chat="album:" +
                            msg['text'])
                    ],
                    [
                        InlineKeyboardButton(
                            text="Search global",
                            switch_inline_query_current_chat=msg['text'])
                    ]
                ]))
def dialog_answer_buttons_3():
    keyboard = ReplyKeyboardMarkup(
        keyboard=[[KeyboardButton(text="По рукам!")]])
    return keyboard
Exemple #25
0
def make_standard_keyboard(buttons):
    return ReplyKeyboardMarkup(keyboard=buttons)
def end_room_buttons():
    keyboard = ReplyKeyboardMarkup(keyboard=[[
        KeyboardButton(
            text="Дверь за спиной мастера Торхилда, ведет в кабинет лорда")
    ], [KeyboardButton(text="Дверь справа – в Библиотеку")]])
    return keyboard
Exemple #27
0
         bot.sendMessage(chat_id, "Li recordem quins productes té actualment per demanar a la propera comanda.")
         c = 1
     # DEFINIM LA VARIABLE b = 1, QUE ENS INDICARÀ SI N'HI HAN PRODUCTES A LA NEVERA O NO. AIXÍ DONCS, SI NO HI HAGUÉS CAP PRODUCTE A LA NEVERA, EL COMANDAMENT ANTERIOR DONARIA ERROR I PER TANT b == 1 NO SERIA POSSIBLE.
     b = 1
     # SUMEM UNA UNITAT A LA VARIABLE n, COSA LA QUAL ENS DONARÀ PAS A AGAFAR EL SEGÜENT ARTICLE QUAN TORNI A EXECUTAR-SE EL COMANDAMENT.
     n = n + 1
     # MULTIPLIQUEM EL PREU PER UNITAT PER LES QUANTITATS DEL ARTICLE QUE COMPRAREM, I HO SUMEM AL PREU TOTAL DE LA COMPRA.
     preutu = float(qpredeterminada) * float(preupu)
     prtotal = float(prtotal) + float(preutu)
     # ENVIAREM EL NOM DE L'ARTICLE, LA QUANTITAT I EL PREU FINAL DELS ARTICLES. HO FAREM EN PLURAL, JA QUE HI HA MÉS D'UN.
     if float(qpredeterminada) > 1:
         bot.sendMessage(chat_id, str(nom) + ", " + str(qpredeterminada) + " articles. Preu de " + str(preutu) + " €")
     # ENVIAREM EL NOM DE L'ARTICLE, LA QUANTITAT I EL PREU DE L'ARTICLE. HO FAREM EN SINGULAR, JA QUE NOMÉS HI HA UN.
     if float (qpredeterminada) == 1:
         bot.sendMessage(chat_id, str(nom) + ", " + str(qpredeterminada) + " artícle. Preu de " + str(preutu) + " €")
 # QUAN HI HAGI CAP ERROR AL CODI ANTERIOR, ÉS A DIR, QUAN L'ARTICLE NÚMERO n NO EXISTEIXI, PASSA A EXECUTAR AQUEST CODI DIRECTAMENT.
 except:
     # SEMPRE QUE t == 0, EXECUTARÀ EL CODI (ÉS A DIR, NOMÉS UNA VEGADA).
     while t == 0:
         # QUAN b == 1 (ÉS A DIR, HI HAN ARTICLES A LA COMANDA) ENVIARÀ UN MISSATGE AMB EL PREU TOTAL DE LA COMANDA I UN ALTRE PREGUNTANT SI VOL FER LA COMANDA O SI BÉ VOL CANVIAR-LA. QUAN CONTESTI A AQUESTA PREGUNTA, SERÀ EL SCRIPT menuprincipal.py QUI AGAFI LA RESPOSTA I ACTUÏ EN CONSEQÜÈNCIA.
         if b == 1:
             bot.sendMessage(chat_id, "El preu total de la compra es de " + str(prtotal) + " €")
             resposta = ReplyKeyboardMarkup(keyboard=[[KeyboardButton(text='Fer comanda')], [KeyboardButton(text='Modificar')], [KeyboardButton(text='Inici')]], one_time_keyboard=True)
             bot.sendMessage(chat_id, "Quina acció desitja realitzar?", reply_markup=resposta)
             t = 1
             a()
         # QUAN b == 0 (ÉS A DIR, NO HI HA CAP ARTICLE A LA COMANDA) ENVIARÀ UN MISSATGE INFORMANT-HO.
         if b == 0:
             resposta = ReplyKeyboardMarkup(keyboard=[[KeyboardButton(text='Inici')]], one_time_keyboard=True)
             bot.sendMessage(chat_id, "No té cap producte per demanar.", reply_markup=resposta)
             a()
Exemple #28
0
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'].lower()
    # bot.sendMessage(chat_id, 'This is noooooot finnal noot wooorking keyboard', reply_markup=ReplyKeyboardMarkup(
    # keyboard=[
    # [KeyboardButton(text="🗓️ Current Weather 🗓️"), KeyboardButton(text="📅 Weekly Weather 📅"),
    # KeyboardButton(text="🔧 Settings 🔧")]
    # ]
    # , resize_keyboard=True))
    if command == '/start':
        markup = ReplyKeyboardMarkup(keyboard=[
            [
                KeyboardButton(text='🗓️ current weather 🗓️'),
                KeyboardButton(text='📅 weekly weather 📅', )
            ],
            [KeyboardButton(text='🔧 settings 🔧')],
        ])
        bot.sendMessage(chat_id,
                        '*Welcome!*',
                        reply_markup=markup,
                        parse_mode='Markdown')
    elif command == '🗓️ current weather 🗓️':
        markup = ReplyKeyboardMarkup(keyboard=[[
            KeyboardButton(text='📌 last location 📌')
        ], [KeyboardButton(
            text='➕ new Location ➕'
        )], [KeyboardButton(text='🗺️ my location 🗺️', request_location=True)
             ], [KeyboardButton(text='🔙 back 🔙')]])
        bot.sendMessage(chat_id,
                        '*Choose location*',
                        reply_markup=markup,
                        parse_mode='Markdown')
    elif command == '📅 weekly weather 📅':
        markup = ReplyKeyboardMarkup(keyboard=[[
            KeyboardButton(text='📌 last location 📌')
        ], [KeyboardButton(
            text='➕ new Location ➕'
        )], [KeyboardButton(text='🗺️ my location 🗺️', request_location=True)
             ], [KeyboardButton(text='🔙 back 🔙')]])
        bot.sendMessage(chat_id,
                        '*Choose location*',
                        reply_markup=markup,
                        parse_mode='Markdown')
    elif command == '🔧 settings 🔧':
        markup = ReplyKeyboardMarkup(keyboard=[[
            KeyboardButton(text='🌐 languages 🌐'),
            KeyboardButton(text='units')
        ], [KeyboardButton(text='alerts'),
            KeyboardButton(text='🔙 back 🔙')]])
        bot.sendMessage(chat_id,
                        '*Set up your bot*',
                        reply_markup=markup,
                        parse_mode='Markdown')
    elif command == '🔙 back 🔙':
        markup = ReplyKeyboardMarkup(keyboard=[
            [
                KeyboardButton(text='🗓️ current weather 🗓️'),
                KeyboardButton(text='📅 weekly weather 📅', )
            ],
            [KeyboardButton(text='🔧 settings 🔧')],
        ])
        bot.sendMessage(chat_id,
                        '*you returned back*',
                        reply_markup=markup,
                        parse_mode='Markdown')
    elif command == 'units':
        markup = ReplyKeyboardMarkup(keyboard=[
            [
                KeyboardButton(text='celsium(°C)'),
                KeyboardButton(text='fahrenheit(°F)', )
            ],
            [KeyboardButton(text='❌ cancel ❌')],
        ])
        bot.sendMessage(chat_id,
                        '*Choose Celsium or Fahrenheit*',
                        reply_markup=markup,
                        parse_mode='Markdown')
    elif command == '❌ cancel ❌':
        markup = ReplyKeyboardMarkup(keyboard=[[
            KeyboardButton(text='🌐 languages 🌐'),
            KeyboardButton(text='units')
        ], [KeyboardButton(text='alerts'),
            KeyboardButton(text='🔙 back 🔙')]])
        bot.sendMessage(chat_id,
                        '*Set up your bot*',
                        reply_markup=markup,
                        parse_mode='Markdown')
    if command == 'celsium(°c)':
        markup = ReplyKeyboardMarkup(keyboard=[
            [
                KeyboardButton(text='🗓️ current weather 🗓️'),
                KeyboardButton(text='📅 weekly weather 📅', )
            ],
            [KeyboardButton(text='🔧 settings 🔧')],
        ])
        bot.sendMessage(chat_id,
                        '*Units now are metric(celsium)*',
                        reply_markup=markup,
                        parse_mode='Markdown')
    if command == 'fahrenheit(°f)':
        markup = ReplyKeyboardMarkup(keyboard=[
            [
                KeyboardButton(text='🗓️ current weather 🗓️'),
                KeyboardButton(text='📅 weekly weather 📅', )
            ],
            [KeyboardButton(text='🔧 settings 🔧')],
        ])
        bot.sendMessage(chat_id,
                        '*Units now are imperial(fahrenheit)*',
                        reply_markup=markup,
                        parse_mode='Markdown')
    if command == '🌐 languages 🌐':
        markup = ReplyKeyboardMarkup(keyboard=[
            [
                KeyboardButton(text='🏴󠁧󠁢󠁥󠁮󠁧󠁿 english 🏴󠁧󠁢󠁥󠁮󠁧󠁿'),
                KeyboardButton(text='🇩🇪 deutsch 🇩🇪', )
            ],
            [
                KeyboardButton(text='🇺🇦 українська 🇺🇦'),
                KeyboardButton(text='🇷🇺 русский 🇷🇺', )
            ],
        ])
        bot.sendMessage(chat_id,
                        '*Units now are imperial(fahrenheit)*',
                        reply_markup=markup,
                        parse_mode='Markdown')
    if command == '🏴󠁧󠁢󠁥󠁮󠁧󠁿 english 🏴':
        markup = ReplyKeyboardMarkup(keyboard=[
            [
                KeyboardButton(text='🗓️ current weather 🗓️'),
                KeyboardButton(text='📅 weekly weather 📅', )
            ],
            [KeyboardButton(text='🔧 settings 🔧')],
        ])
        bot.sendMessage(chat_id,
                        '*Your language changed to English*',
                        reply_markup=markup,
                        parse_mode='Markdown')

        #ukrainian section

    if command == '🇺🇦 українська 🇺🇦':
        markup = ReplyKeyboardMarkup(keyboard=[
            [
                KeyboardButton(text='🗓️ поточна погода 🗓️'),
                KeyboardButton(text='📅 тижнева погода 📅', )
            ],
            [KeyboardButton(text='🔧 налаштування 🔧')],
        ])
        bot.sendMessage(chat_id,
                        '*Ваша мова була змінена на Українську*',
                        reply_markup=markup,
                        parse_mode='Markdown')
    elif command == '🗓️ поточна погода 🗓️':
        markup = ReplyKeyboardMarkup(keyboard=[[
            KeyboardButton(text='📌 останнє місце 📌')
        ], [KeyboardButton(text='➕ нове місце ➕')
            ], [KeyboardButton(text='🗺️ моє місце 🗺️', request_location=True)
                ], [KeyboardButton(text='🔙 назад 🔙')]])
        bot.sendMessage(chat_id,
                        '*Виберіть місцезнаходження*',
                        reply_markup=markup,
                        parse_mode='Markdown')
    elif command == '📅 тижнева погода 📅':
        markup = ReplyKeyboardMarkup(keyboard=[[
            KeyboardButton(text='📌 останнє місце 📌')
        ], [KeyboardButton(text='➕ нове місце ➕')
            ], [KeyboardButton(text='🗺️ моє місце 🗺️', request_location=True)
                ], [KeyboardButton(text='🔙 назад 🔙')]])
        bot.sendMessage(chat_id,
                        '*Виберіть місцезнаходження*',
                        reply_markup=markup,
                        parse_mode='Markdown')
    elif command == '🔧 налаштування 🔧':
        markup = ReplyKeyboardMarkup(keyboard=[[
            KeyboardButton(text='🌐 мови 🌐'),
            KeyboardButton(text='одиниці')
        ], [
            KeyboardButton(text='сповіщення'),
            KeyboardButton(text='🔙 назад 🔙')
        ]])
        bot.sendMessage(chat_id,
                        '*Налаштуйте свого бота*',
                        reply_markup=markup,
                        parse_mode='Markdown')
    elif command == '🔙 назад 🔙':
        markup = ReplyKeyboardMarkup(keyboard=[
            [
                KeyboardButton(text='🗓️ поточна погода 🗓️'),
                KeyboardButton(text='📅 тижнева погода 📅', )
            ],
            [KeyboardButton(text='🔧 налаштування 🔧')],
        ])
        bot.sendMessage(chat_id,
                        '*Ви повернулися назад*',
                        reply_markup=markup,
                        parse_mode='Markdown')
    elif command == 'одиниці':
        markup = ReplyKeyboardMarkup(keyboard=[
            [
                KeyboardButton(text='цельсії(°C)'),
                KeyboardButton(text='фаренгейти(°F)', )
            ],
            [KeyboardButton(text='❌ відмінити ❌')],
        ])
        bot.sendMessage(chat_id,
                        '*Виберіть одиниці виміру*',
                        reply_markup=markup,
                        parse_mode='Markdown')
    elif command == '❌ відмінити ❌':
        markup = ReplyKeyboardMarkup(keyboard=[[
            KeyboardButton(text='🌐 мови 🌐'),
            KeyboardButton(text='одиниці')
        ], [
            KeyboardButton(text='сповіщення'),
            KeyboardButton(text='🔙 назад 🔙')
        ]])
        bot.sendMessage(chat_id,
                        '*налаштуйте свого бота*',
                        reply_markup=markup,
                        parse_mode='Markdown')
    if command == 'цельсії(°c)':
        markup = ReplyKeyboardMarkup(keyboard=[
            [
                KeyboardButton(text='🗓️ поточна погода 🗓️'),
                KeyboardButton(text='📅 тижнева погода 📅', )
            ],
            [KeyboardButton(text='🔧 налаштування 🔧')],
        ])
        bot.sendMessage(chat_id,
                        '*Одиниці виміру були змінені на цельсії*',
                        reply_markup=markup,
                        parse_mode='Markdown')
    if command == 'фаренгейти(°f)':
        markup = ReplyKeyboardMarkup(keyboard=[
            [
                KeyboardButton(text='🗓️ поточна погода 🗓️'),
                KeyboardButton(text='📅 тижнева погода 📅', )
            ],
            [KeyboardButton(text='🔧 налаштування 🔧')],
        ])
        bot.sendMessage(chat_id,
                        '*Одиниці виміру були змінені на фаренгейти*',
                        reply_markup=markup,
                        parse_mode='Markdown')
    if command == '🌐 мови 🌐':
        markup = ReplyKeyboardMarkup(keyboard=[
            [
                KeyboardButton(text='🏴󠁧󠁢󠁥󠁮󠁧󠁿 english 🏴󠁧󠁢󠁥󠁮󠁧󠁿'),
                KeyboardButton(text='🇩🇪 deutsch 🇩🇪', )
            ],
            [
                KeyboardButton(text='🇺🇦 українська 🇺🇦'),
                KeyboardButton(text='🇷🇺 русский 🇷🇺', )
            ],
        ])
        bot.sendMessage(chat_id,
                        '*Виберіть мову*',
                        reply_markup=markup,
                        parse_mode='Markdown')
Exemple #29
0
def get_events():
    msg = '''
    Join us for an incredible party the Thursday in our Marina Bay Sands shop!
    '''
    return msg


COMMANDS = {
    'help': get_help,
    'offers': get_offers,
    'events': get_events,
}

# Create a custom keyboard with only the valid responses
keys = [[KeyboardButton(text=text)] for text in COMMANDS]
KEYBOARD = ReplyKeyboardMarkup(keyboard=keys)


class MarketingBot(telepot.helper.ChatHandler):
    def open(self, initial_msg, seed):
        self.sender.sendMessage(get_help(), reply_markup=KEYBOARD)
        # prevent on_message() from being called on the initial message
        return True

    def on_chat_message(self, msg):
        # If the data sent is not test, return an error
        content_type, chat_type, chat_id = telepot.glance(msg)

        if content_type != 'text':
            self.sender.sendMessage(
                "I don't understand you. "
def start(msg):
	global free

	content_type, chat_type, chat_id = telepot.glance(msg)

	if free == 0 and chat_id != root:
		return

	if check_flood(chat_id, msg['date']) == "BANNED" and chat_id != root:
		return

	pprint(msg)
	statisc(chat_id, "USERS")
	init_user(chat_id, msg)

	if content_type == "text" and msg['text'] == "/start":
		try:
			sendPhoto(
				chat_id, open("example.jpg", "rb"),
				caption = "Welcome to @%s \nPress '/' to get commands list" % bot_name
			)
		except FileNotFoundError:
			pass

		sendMessage(
			chat_id,
			"Press for search what you prefer" +
			"\nP.S. Remember you can do this digiting @ in your keyboard and select %s" % bot_name +
			"\nSend a Deezer or Spotify link to download \nSend a song o vocal message to recognize the track",
			reply_markup = InlineKeyboardMarkup(
				inline_keyboard = [
					[
						InlineKeyboardButton(
							text = "Search by artist 👤",
							switch_inline_query_current_chat = "art: "
						),
						InlineKeyboardButton(
							text = "Search by album 💽",
							switch_inline_query_current_chat = "alb: "
						)
					],
					[
						InlineKeyboardButton(
							text = "Search playlist 📂",
							switch_inline_query_current_chat = "pla: "
						),
						InlineKeyboardButton(
								text = "Search label 📀",
								switch_inline_query_current_chat = "lbl: "
							)
					],
					[
						InlineKeyboardButton(
							text = "Search track 🎧",
							switch_inline_query_current_chat = "trk: "
						),
						InlineKeyboardButton(
							text = "Global search 📊",
							switch_inline_query_current_chat = ""
						)
					]
				]
			)
		)

	elif content_type == "text" and msg['text'] == "/translator":
		if users[chat_id]['tongue'] != "en":
			users[chat_id]['tongue'] = "en"
			sendMessage(chat_id, "Now the language is english")
		else:
			users[chat_id]['tongue'] = msg['from']['language_code']
			sendMessage(chat_id, "Now the bot will use the Telegram app language")

	elif content_type == "text" and msg['text'] == "/quality":
		sendMessage(
			chat_id, "Select default download quality\nCURRENTLY: %s 🔊" % users[chat_id]['quality'],
			reply_markup = ReplyKeyboardMarkup(
				keyboard = [
					[
						KeyboardButton(
							text = "FLAC"
						),
						KeyboardButton(
							text = "MP3_320Kbps"
						)
					],
					[
						KeyboardButton(
							text = "MP3_256Kbps"
						),
						KeyboardButton(
							text = "MP3_128Kbps"
						)
					]
				]
			)
		)

	elif content_type == "text" and (
		msg['text'] == "FLAC" or 
		msg['text'] == "MP3_320Kbps" or 
		msg['text'] == "MP3_256Kbps" or 
		msg['text'] == "MP3_128Kbps"
	):
		users[chat_id]['quality'] = msg['text'].replace("Kbps", "")

		sendMessage(
			chat_id, "Songs will be downloaded in %s quality 🔊" % msg['text'],
			reply_markup = ReplyKeyboardRemove()
		)

		sendMessage(chat_id, "Songs which cannot be downloaded in quality you have chosen will be downloaded in the best quality possible")

	elif content_type == "voice" or content_type == "audio":
		Thread(
			target = Audio,
			args = (msg[content_type]['file_id'], chat_id)
		).start()

	elif content_type == "text" and msg['text'] == "/info":
		sendMessage(
			chat_id,
			"🔺 Version: %s \n🔻 Name: @%s \n✒️ Creator: @%s \n💵 Donation: %s \n📣 Forum: %s \n👥 Users: %d \n⬇️ Total downloads: %d"
			% (
				version,
				bot_name,
				creator,
				donation_link,
				group_link,
				statisc(chat_id, "USERS"),
				statisc(chat_id, "TRACKS")
			)
		)

	elif content_type == "text" and chat_id == root and "the cat is on the table" in msg['text']:
		what = msg['text'].split("the cat is on the table ")[-1]

		if what == "1":
			free = 1

		elif what == "0":
			free = 0

		else:
			Thread(
				target = sendall,
				args = (what,)
			).start()

	elif content_type == "text":
		text = msg['text'].replace("'", "")

		try:
			msg['entities']

			if ans == "2" and users[chat_id]['c_downloads'] == 3:
				sendMessage(chat_id, "Wait the end and repeat the step, did you think you could download how much songs you wanted? ;)")
			else:
				if ans == "2":
					users[chat_id]['c_downloads'] += 1

				Thread(
					target = Link,
					args = (
						text, chat_id,
						users[chat_id]['quality'], msg
					)
				).start()
		except KeyError:
			sendMessage(chat_id, "Press",
				reply_markup = InlineKeyboardMarkup(
					inline_keyboard = [
						[
							InlineKeyboardButton(
								text = "Search artist 👤",
								switch_inline_query_current_chat = "art: %s" % text
							),
							InlineKeyboardButton(
								text = "Search album 💽",
								switch_inline_query_current_chat = "alb: %s" % text
							)
						],
						[
							InlineKeyboardButton(
								text = "Search playlist 📂",
								switch_inline_query_current_chat = "pla: %s" % text
							),
							InlineKeyboardButton(
								text = "Search label 📀",
								switch_inline_query_current_chat = "lbl: %s" % text
							)
						],
						[
							InlineKeyboardButton(
								text = "Search track 🎧",
								switch_inline_query_current_chat = "trk: %s" % text
							),
							InlineKeyboardButton(
								text = "Search global 📊",
								switch_inline_query_current_chat = text
							)
						]
					]
				)
			)