Ejemplo n.º 1
0
class Lover(telepot.helper.ChatHandler):
    keyboard = ReplyKeyboardMarkup(keyboard=[[ #<-- Menu awal
                   KeyboardButton(text='Beri Pakan'),
                   KeyboardButton(text='Pengaturan')], [
                   KeyboardButton(text='UMmm ...'),
                   KeyboardButton(text='Keluar')
               ]], one_time_keyboard=True)
    keyboard1 = ReplyKeyboardMarkup(keyboard=[[ #<-- Terusan Pengaturan dari Menu Awal
                   KeyboardButton(text='Set Penjadwalan Pemberian Pakan')], [
                   KeyboardButton(text='Set Dosis Pemberian Pakan')
               ]], one_time_keyboard=True)
    keyboard2 = ReplyKeyboardMarkup(keyboard=[[ #-- Terusan Pengaturan-Takaran dari Menu Awal
                   KeyboardButton(text='Jadwal Kolam 1'),
                   KeyboardButton(text='Jadwal Kolam 2')], [
                   KeyboardButton(text='Jadwal Kolam 3'),
                   KeyboardButton(text='Jadwal Semua Kolam')], [
                   KeyboardButton(text='Kembali')
               ]], one_time_keyboard=True)
    keyboard3 = ReplyKeyboardMarkup(keyboard=[[ #<-- Terusan Pengaturan-Waktu dari Menu Awal
                   KeyboardButton(text='Dosis Kolam 1'),
                   KeyboardButton(text='Dosis Kolam 2')], [
                   KeyboardButton(text='Dosis Kolam 3'),
                   KeyboardButton(text='Dosis Semua Kolam')], [
                   KeyboardButton(text='Kembali')
               ]], one_time_keyboard=True)
    keyboard4 = InlineKeyboardMarkup(inline_keyboard=[[ #-- Terusan Pengaturan-Takaran dari Menu Awal
                   InlineKeyboardButton(text='00:00', callback_data='0'),
                   InlineKeyboardButton(text='01:00', callback_data='1'), 
                   InlineKeyboardButton(text='02:00', callback_data='2'),
                   InlineKeyboardButton(text='03:00', callback_data='3')],[
                   InlineKeyboardButton(text='04:00', callback_data='4'),
                   InlineKeyboardButton(text='05:00', callback_data='5'), 
                   InlineKeyboardButton(text='06:00', callback_data='6'),
                   InlineKeyboardButton(text='07:00', callback_data='7')],[
                   InlineKeyboardButton(text='08:00', callback_data='8'),
                   InlineKeyboardButton(text='09:00', callback_data='9'), 
                   InlineKeyboardButton(text='10:00', callback_data='10'),
                   InlineKeyboardButton(text='11:00', callback_data='11')],[
                   InlineKeyboardButton(text='12:00', callback_data='12'),
                   InlineKeyboardButton(text='13:00', callback_data='13'), 
                   InlineKeyboardButton(text='14:00', callback_data='14'),
                   InlineKeyboardButton(text='15:00', callback_data='15')],[
                   InlineKeyboardButton(text='16:00', callback_data='16'),
                   InlineKeyboardButton(text='17:00', callback_data='17'), 
                   InlineKeyboardButton(text='18:00', callback_data='18'),
                   InlineKeyboardButton(text='19:00', callback_data='19')],[
                   InlineKeyboardButton(text='20:00', callback_data='20'),
                   InlineKeyboardButton(text='21:00', callback_data='21'), 
                   InlineKeyboardButton(text='22:00', callback_data='22'),
                   InlineKeyboardButton(text='23:00', callback_data='23')],[
                   InlineKeyboardButton(text='Kembali', callback_data='kembali')
               ]], resize_keyboard=True, one_time_keyboard=True)
    keyboard5 = ReplyKeyboardMarkup(keyboard=[[ 
                   KeyboardButton(text='Pakan Kolam 1'),
                   KeyboardButton(text='Pakan Kolam 2')], [
                   KeyboardButton(text='Pakan Kolam 3'),
                   KeyboardButton(text='Pakan Semua Kolam')], [
                   KeyboardButton(text='Kembali')
               ]], one_time_keyboard=True)

    def __init__(self, *args, **kwargs):
        super(Lover, self).__init__(*args, **kwargs)

        # Retrieve from database
        global propose_records
        if self.id in propose_records:
            self._edit_msg_ident = propose_records[self.id]
            self._editor = telepot.helper.Editor(self.bot, self._edit_msg_ident) if self._edit_msg_ident else None
        else:
            self._edit_msg_ident = None
            self._editor = None

    def _propose(self):
        sent = self.sender.sendMessage('Apa yang perlu saya lakukan ?', reply_markup=self.keyboard)
        self._editor = telepot.helper.Editor(self.bot, sent)
        self._edit_msg_ident = telepot.message_identifier(sent)
    
    """
    def _propose_time(self):
        current_time = time.strftime("%H:%M", t)
        (h, m) = current_time.split(':')
        result = int(h) * 3600 + int(m) * 60
        
        (h, m) = setTime1.split(':')
        timeklm1 = int(h) * 3600 + int(m) * 60
        
        (h, m) = setTime2.split(':')
        timeklm2 = int(h) * 3600 + int(m) * 60
        
        (h, m) = setTime3.split(':')
        timeklm3 = int(h) * 3600 + int(m) * 60
    """

    def _cancel_last(self):
        if self._editor:
            self._editor.editMessageReplyMarkup(reply_markup=None)
            self._editor = None
            self._edit_msg_ident = None

    def on_chat_message(self, msg):
        global jadwal_1
        global jadwal_2
        global jadwal_3
        global takar_1
        global takar_2
        global takar_3
        global status_1
        global status_2
        global status_3

        chat_id = msg['chat']['id']
        if msg['from']['id'] != CHATID:
            bot.sendMessage(chat_id, "Maaf ini adalah bot pribadi. Akses ditolak!")
            self.close()
        
        command = msg['text']
        if (command == 'Keluar'):
            sent = self.sender.sendMessage("Terima kasih! \nBye..")
            self._editor = telepot.helper.Editor(self.bot, sent)
            self._edit_msg_ident = telepot.message_identifier(sent)
            self.close()
        #== bagian pengaturan ==
        elif (command == 'Pengaturan'):
            sent = self.sender.sendMessage('Apa yang ingin Anda atur?', reply_markup=self.keyboard1)
            self._editor = telepot.helper.Editor(self.bot, sent)
            self._edit_msg_ident = telepot.message_identifier(sent)
        elif (command == 'Set Penjadwalan Pemberian Pakan'):
            sent = self.sender.sendMessage('Kolam mana yang ingi Anda atur <b><i>Penjadwalan</i></b> Pakannya ?', parse_mode='html', reply_markup=self.keyboard2)
            self._editor = telepot.helper.Editor(self.bot, sent)
            self._edit_msg_ident = telepot.message_identifier(sent)
        elif (command == 'Set Dosis Pemberian Pakan'):
            sent = self.sender.sendMessage('Kolam mana yang ingi Anda atur <b><i>Dosis</i></b> Pakannya ?', parse_mode='html', reply_markup=self.keyboard3)
            self._editor = telepot.helper.Editor(self.bot, sent)
            self._edit_msg_ident = telepot.message_identifier(sent)
        elif (command == 'Jadwal Kolam 1'):
            status_1 = True
            status_2 = False
            status_3 = False
            sent = self.sender.sendMessage('Silahkan pilih waktu penjadwalan pakan..', reply_markup=self.keyboard4 )
            self._editor = telepot.helper.Editor(self.bot, sent)
            self._edit_msg_ident = telepot.message_identifier(sent)
        elif (command == 'Jadwal Kolam 2'):
            status_1 = False
            status_2 = True
            status_3 = False
            sent = self.sender.sendMessage('Silahkan pilih waktu penjadwalan pakan..', reply_markup=self.keyboard4 )
            self._editor = telepot.helper.Editor(self.bot, sent)
            self._edit_msg_ident = telepot.message_identifier(sent)
        elif (command == 'Jadwal Kolam 3'):
            status_1 = False
            status_2 = False
            status_3 = True
            sent = self.sender.sendMessage('Silahkan pilih waktu penjadwalan pakan..', reply_markup=self.keyboard4 )
            self._editor = telepot.helper.Editor(self.bot, sent)
            self._edit_msg_ident = telepot.message_identifier(sent)
        elif (command == 'Jadwal Semua Kolam'):
            status_1 = True
            status_2 = True
            status_3 = True
            sent = self.sender.sendMessage('Silahkan pilih waktu penjadwalan pakan..', reply_markup=self.keyboard4 )
            self._editor = telepot.helper.Editor(self.bot, sent)
            self._edit_msg_ident = telepot.message_identifier(sent)
        #== end pengaturan ==
        else :
            self._propose()
        
        #self._cancel_last()      

    def on_callback_query(self, msg):
        global jadwal_1
        global jadwal_2
        global jadwal_3
        global takar_1
        global takar_2
        global takar_3
        global status_1
        global status_2
        global status_3
        
        query_id, from_id, query_data = telepot.glance(msg, flavor='callback_query')
            
        # == Setting Penjadwalan ==              
        if query_data == '1':
            self.bot.answerCallbackQuery(query_id, text='Ok. Penjadwalan tersimpan..')
            self._cancel_last()
            text = 'Penjadwalan pemberian Pakan pada kolam '
            if (status_1):
                text += '1, '
                jadwal_1 = 1
                status_1 = False
            if (status_2):
                text += '2, '
                jadwal_2 = 1
                status_2 = False
            if (status_3):
                text += '3, '
                jadwal_3 = 1
                status_3 = False
            text += 'telah diset ke jam 01:00'
            sent = self.sender.sendMessage(text)
            self._editor = telepot.helper.Editor(self.bot, sent)
            self._edit_msg_ident = telepot.message_identifier(sent)
            self.close()
            
        elif query_data == 'dosis':
            self.bot.answerCallbackQuery(query_id, text='Ok. Pertanyaan berikutnya...')
            self._cancel_last()
            sent = self.sender.sendMessage('Kolam mana yang ingin anda atur dosis pakannya?', reply_markup=self.keyboard4)
            self._editor = telepot.helper.Editor(self.bot, sent)
            self._edit_msg_ident = telepot.message_identifier(sent)
            
        # ==pemberian pakan==            
        elif query_data == 'pakan':
            self.bot.answerCallbackQuery(query_id, text='Ok. Pertanyaan berikutnya...')
            self._cancel_last()
            sent = self.sender.sendMessage('Kolam mana yang ingin anda beri pakan?', reply_markup=self.keyboard2)
            self._editor = telepot.helper.Editor(self.bot, sent)
            self._edit_msg_ident = telepot.message_identifier(sent)
                 
        elif query_data == 'pknk1':
            if setTime1 == 'null' :
                self.bot.answerCallbackQuery(query_id, text='Ok. Pemberian pakan pada kolam 1 akan dilakukan...')
                self._cancel_last()
                #!! kasi pakan, kamera jalan,
                stat1 = 1
                self.sender.sendMessage('Pemberian pakan pada kolam 1 telah selesai \nketikkan perintah /dokumentasi untuk mendapat rekaman video..')
                self.close()
            else :
                if stat1 == 0 :
                    self.bot.answerCallbackQuery(query_id, text='Peringatan !!!')
                    self._cancel_last()
                    self.sender.sendMessage('Pemberian pakan pada kolam 1 Telah dijadwlkan pada pukul' + setTime1 + '\nketikkan perintah /force1 untuk memberikan pakan sekarang juga..')
                    self.close()
            
        else:
            self.bot.answerCallbackQuery(query_id, text='Ok. Tapi aku akan terus bertanya.')
            self._cancel_last()
            self._propose()
    
    def on__idle(self, event):
        global status_1
        global status_2
        global status_3
        if status_1 or status_2 or status_3 :
            self.sender.sendMessage('Saya tahu Anda mungkin perlu sedikit waktu. Aku akan selalu di sini untukmu.')
            self._cancel_last()
        self.close()
    
    def on_close(self, ex):
        # Save to database
        global propose_records
        propose_records[self.id] = (self._edit_msg_ident)
Ejemplo n.º 2
0
    def on_chat_message(self, msg):
        global state, stall, stall1, can
        content_type, chat_type, chat_id = telepot.glance(msg)
        if content_type == 'text':

            # get message payload
            msg_text = msg['text']

            if (msg_text.startswith('/')):

                # parse the command excluding the '/'
                command = msg_text[1:].lower()

                # prepare the correct response based on the given command
                if (command == 'start'):
                    #display current weather at start of bot
                    weather = Weather()

                    # Lookup WOEID via http://weather.yahoo.com.
                    client = yweather.Client()
                    Singapore_NTU = client.fetch_woeid(
                        'Nanyang Technological University')
                    lookup = weather.lookup(Singapore_NTU)
                    condition = lookup.condition()
                    response = "Current Weather in NTU: " + condition[
                        'text'] + '\n\nRating Stalls or Finding Food? \nTo Rate a Stall, enter /rate\nTo Find Food, enter /find \n\nTo view all commands, enter /list'
                    bot.sendMessage(chat_id, response)

                elif (command == 'list'):
                    #dispaly list of avaiable commands
                    response = 'Here are a list of all available commands: \n/start Begin your food journey! \n/rate Rate your dining experience at stall! \n/find Find delicious food by location or cuisine! \n/feedback Send any feedback, queries or errors spotted to us! \n/quit Exit what you are doing'
                    bot.sendMessage(chat_id, response)
                elif (command == 'feedback'):
                    #set state to 4 to receive feedback from user
                    self.state = 4
                    bot.sendMessage(chat_id,
                                    'Please enter feedback your feedback!')
                elif (command == 'rate'):
                    #set state to 1 to proceed to next stage of rating process
                    self.state = 1
                    canlist = [
                        'Canteen 1', 'Canteen 2', 'Canteen 4', 'Canteen 9',
                        'Canteen 11', 'Canteen 13', 'Canteen 14', 'Canteen 16',
                        'Koufu', 'NIE Canteen', 'North Hill Canteen',
                        'North Spine Foodcourt', 'Pioneer Canteen'
                    ]
                    rm = ReplyKeyboardMarkup(
                        one_time_keyboard=True,
                        keyboard=[[KeyboardButton(text=i)] for i in canlist])
                    bot.sendMessage(chat_id, 'Choose Canteen', reply_markup=rm)

                elif (command == 'find'):
                    response = 'Filter by Canteen or Cuisine?'
                    confirm_keyboard = InlineKeyboardMarkup(inline_keyboard=[
                        [
                            InlineKeyboardButton(text='Canteen',
                                                 callback_data='can')
                        ],
                        [
                            InlineKeyboardButton(text='Cuisine',
                                                 callback_data='cui')
                        ],
                    ])
                    bot.sendMessage(chat_id,
                                    response,
                                    reply_markup=confirm_keyboard)
                elif (command == 'quit'):
                    #used to exit and reset to initial state
                    self.state = 0
            elif (self.state == 0):
                #initial state. Prompt if no valid command is entered
                bot.sendMessage(
                    chat_id,
                    "Hi, please enter /start to begin! \n\nFor feedback, please enter \n/feedback \n\nTo exit at anytime, enter /quit"
                )
            elif (self.state == 1):
                self.check = 0
                conn_string = "host='ec2-54-225-237-64.compute-1.amazonaws.com' dbname='d7dkk1sep0usei' user='******' password='******'"
                conn = psycopg2.connect(conn_string)
                cursor = conn.cursor()
                cursor.execute("SELECT * FROM store")
                rlist = cursor.fetchall()

                #check if user input for canteen is valid (matches with that in master list from database table "store")
                for i in range(len(rlist)):
                    if (msg_text == rlist[i][0]):
                        self.check = 1
                #if input valid, we set state to the next state, and prompt user for input of stall
                if (self.check):
                    can = msg_text
                    otpt = "List of stalls in " + msg_text + "\n"
                    self.stall = []
                    #find list of stalls in selected canteen
                    for i in range(0, len(rlist)):
                        if (rlist[i][0] == msg_text):
                            otpt = otpt + rlist[i][2] + "\n"
                            self.stall.append(rlist[i][2])
                    RM = ReplyKeyboardMarkup(
                        one_time_keyboard=True,
                        keyboard=[[KeyboardButton(text=stall)]
                                  for stall in self.stall])

                    bot.sendMessage(chat_id, otpt, reply_markup=RM)
                    self.state = 2
                #if input invalid, stay at current state and prompt user for input of canteen again
                else:
                    canlist = [
                        'Canteen 1', 'Canteen 2', 'Canteen 4', 'Canteen 9',
                        'Canteen 11', 'Canteen 13', 'Canteen 14', 'Canteen 16',
                        'Koufu', 'NIE Canteen', 'North Hill Canteen',
                        'North Spine Foodcourt', 'Pioneer Canteen'
                    ]
                    rm = ReplyKeyboardMarkup(
                        one_time_keyboard=True,
                        keyboard=[[KeyboardButton(text=i)] for i in canlist])
                    bot.sendMessage(chat_id, 'Choose Canteen', reply_markup=rm)
                    self.state = 1

            elif (self.state == 2):
                self.check = 0
                #check if user input of stall is valid
                for i in range(len(self.stall)):
                    if (msg_text == self.stall[i]):
                        self.check = 1
                #for valid input, ask user to input ratings and move to next state, state 3
                if (self.check == 1):
                    self.stall1 = msg_text
                    self.state = 3
                    RM = ReplyKeyboardMarkup(
                        one_time_keyboard=True,
                        keyboard=[[KeyboardButton(text=rating)]
                                  for rating in ['5', '4', '3', '2', '1']])
                    bot.sendMessage(chat_id, "Input Ratings", reply_markup=RM)
                #for invalid stall input, prompt user for input of stall, while remaining at current state
                else:
                    bot.sendMessage(chat_id,
                                    "Input Stall: ",
                                    reply_markup=ReplyKeyboardMarkup(
                                        one_time_keyboard=True,
                                        keyboard=[[KeyboardButton(text=stall)]
                                                  for stall in self.stall]))

            elif (self.state == 3):
                #for valid rating input, attempt to save review using rate.py. check for multiple rating by single user is made in rate.py
                if ((msg_text == '1') | (msg_text == '2') | (msg_text == '3') |
                    (msg_text == '4') | (msg_text == '5')):
                    self.state = 0
                    bot.sendMessage(
                        chat_id, rate(can, self.stall1, msg_text,
                                      str(chat_id)))
                #for invalid rating input, prompt user for rating input and remain at current state
                else:
                    self.state = 3
                    bot.sendMessage(
                        chat_id,
                        "Input Ratings",
                        reply_markup=ReplyKeyboardMarkup(
                            one_time_keyboard=True,
                            keyboard=[[KeyboardButton(text=rating)]
                                      for rating in ['5', '4', '3', '2', '1']
                                      ]))
            elif (self.state == 4):
                #send feedback and userid to the admin and return to initial state
                response = str(msg_text) + '\nUserID : ' + str(chat_id)
                bot.sendMessage(408469886, response)
                bot.sendMessage(chat_id,
                                'Thank you, your feedback was recorded!')
                self.state = 0
Ejemplo n.º 3
0
 def create_url_inline_query(self):
     data = []
     for elem in self.tree.get_topic_list():
         data.append([self.create_url_button(elem)])
     return InlineKeyboardMarkup(inline_keyboard=data)
Ejemplo n.º 4
0
        def on_chat_message(msg):
            content_type, chat_type, chat_id = telepot.glance(msg)
            if(getUserState(chat_id) is None):
                print("new user", chat_id)
                userstate = UserState(chat_id)
                users.append(userstate)


            userstate = getUserState(chat_id)
            msg = msg['text']
            print(chat_id, msg)   
            if(not bePolite(chat_id, msg)): 
                #initialize state
                userstate.__init__(chat_id)
                return

            studentSet = getStudentSet(chat_id)
            if(len(studentSet) == 0):
                userstate.setting_done = False
            else:
                userstate.setting_done = True
                student = studentSet[0]

            service_keyboard = ReplyKeyboardMarkup(
                                keyboard=[
                                    [KeyboardButton(text=SUBSRIBE),KeyboardButton(text=COURSENOTI)], 
                                    [KeyboardButton(text=SEARCHFOOD),KeyboardButton(text=GPAFORECAST)],
                                    [KeyboardButton(text=USERSETTING),KeyboardButton(text=COUSRESRCH)]
                                ]
                            )     

            # state      
            if(userstate.general_state):
                if(msg == SUBSRIBE):
                    userstate.sub_state = True
                    userstate.general_state = False
                elif(msg == COURSENOTI):
                    userstate.coursenotf_state = True   
                    userstate.general_state = False                 
                elif(msg == SEARCHFOOD):
                    userstate.food_state = True
                    userstate.general_state = False
                elif(msg == GPAFORECAST):
                    userstate.gpa_state = True 
                    userstate.general_state = False                   
                elif(msg == USERSETTING):
                    userstate.setting_state = True
                    userstate.general_state = False
                elif(msg == COUSRESRCH):
                    userstate.search_course_state = True
                    userstate.general_state = False

             #使用者設定
            if(userstate.setting_state or (not userstate.setting_done)):
                if(userstate.setting_confirm_state):
                    flag = True
                    buff = msg.split("#")
                    # Check input
                    if (len(buff) != 3):
                        flag = False
                    for token in buff:
                        if(len(token) == 0):
                            flag = False
                    print(buff)
                    if(flag):                        
                        # save the user settings
                        # @DB involves, record Student attr.
                        bot.sendMessage(chat_id, "設定成功")
                        if(not userstate.setting_done):
                            newStudent = Student(sid = buff[0], name = buff[1], department = buff[2], chat_id = chat_id)
                            newStudent.save()
                            userstate.setting_done = True                        
                            bot.sendMessage(chat_id, '您好,請問您需要什麼服務?', reply_markup=service_keyboard)
                        else:
                            # 用 sid 找到要更新的人 (目前未擋幫別人更新)
                            updateStudentSet = Student.objects.filter(sid = buff[0])
                            updateStudentSet.update(name = buff[1], department = buff[2])
                        
                    else:
                        bot.sendMessage(chat_id, "設定失敗")
                    # state release
                    userstate.setting_confirm_state = False
                    userstate.setting_state = False
                    userstate.general_state = True
                    return

                    
                if(not userstate.setting_done):
                    bot.sendMessage(chat_id, "您需要設定個人的資料以利我們提供服務!\n\n請輸入 '學號#姓名#系所' 設定,中間以#字隔開")                   
                else:
                    bot.sendMessage(chat_id, "目前的使用者:\n" + "姓名: " + student.name + "\n學號:" + student.sid + " \n系級:" + student.department)
                    bot.sendMessage(chat_id, "請輸入 '學號#姓名#系所' 更新設定,中間以#字隔開")
                userstate.setting_confirm_state = True
                return

            # 訂閱課程
            if(userstate.sub_state):  
                #  決定是否訂閱              
                if(userstate.sub_course_state):
                    # msg = 識別碼
                    # @DB involves, handle and find the course
                    # exception handling if course doesn't exists                                    
                    # display course information 
                    course_set = Course.objects.filter(cid = msg)
                    if(len(course_set) == 0):
                        bot.sendMessage(chat_id, "找不到該課程!")
                    else:
                        target_course = course_set[0]
                        bot.sendMessage(chat_id, "課程識別碼: " + target_course.cid + "\n課程名稱: " + target_course.name + "\n上課時間: " + target_course.time + "\n課程網課號: " + target_course.courseNum)             
                        # @DB involves, callback_data = "SUB_" + COURSEID   
                        inline_keyboard = InlineKeyboardMarkup(inline_keyboard=[
                           [InlineKeyboardButton(text='Yes', callback_data='SUB_' + target_course.cid + '_' + str(chat_id)), InlineKeyboardButton(text='No', callback_data='SUB_FAIL')],
                        ])
                        bot.sendMessage(chat_id, "確定訂閱?", reply_markup=inline_keyboard)

                    # state release
                    userstate.sub_course_state = False
                    userstate.sub_state = False
                    userstate.general_state = True
                    return


                # 輸入訂閱識別碼
                bot.sendMessage(chat_id, "請輸入您要訂閱的識別碼:")
                if(userstate.sub_course_state == False):
                    userstate.sub_course_state = True
                    return



            # 課程通知
            if(userstate.coursenotf_state):   
                # 決定通知項目               
                if(userstate.coursenotf_course_state):
                    # msg = 識別碼
                    # @DB involves, handle and find the course
                    # exception handling if course doesn't exists
                    course_set = Course.objects.filter(cid = msg)
                    if(len(course_set) == 0):
                        bot.sendMessage(chat_id, "找不到該課程!")

                    inline_keyboard = InlineKeyboardMarkup(inline_keyboard=[
                       [InlineKeyboardButton(text="點名", callback_data='NOTF_ROLL_' + msg), InlineKeyboardButton(text="作業", callback_data='NOTF_HW_' + msg)],
                    ])
                    bot.sendMessage(chat_id, "請問是課程還是作業通知呢?", reply_markup=inline_keyboard)

                    # state release
                    userstate.coursenotf_state = False
                    userstate.coursenotf_course_state = False
                    userstate.general_state = True
                    return
                # 輸入通知識別碼
                bot.sendMessage(chat_id, "請輸入要通知的識別碼:")
                userstate.coursenotf_course_state = True




            # 美食
            if(userstate.food_state):
                userstate.food_state = False
                userstate.general_state = True



            # GPA 預測
            if(userstate.gpa_state):
                forecastCourseID  = ""
                UserSelfPr = 50

                # Forecasrt result
                if(userstate.gpa_getGPA_state):   
                    UserSelfPr = msg                 
                    ResultGrade = forecastUserGrade(forecastCourseID, UserSelfPr)
                    bot.sendMessage(chat_id, "預測的等第:" + ResultGrade,reply_markup=service_keyboard)

                    # state release
                    userstate.gpa_getGPA_state = False
                    userstate.gpa_myGPA_state = False
                    userstate.gpa_state = False
                    userstate.general_state = True
                    return

                # 輸入PR值
                if(userstate.gpa_myGPA_state):
                    # save the courseID
                    # @DB involves, handle and find the course
                    # exception handling if course doesn't exists 
                    course_set = Course.objects.filter(cid = msg)
                    if(len(course_set) == 0):
                        bot.sendMessage(chat_id, "找不到該課程!")  
                        # state release
                        userstate.gpa_getGPA_state = False
                        userstate.gpa_myGPA_state = False
                        userstate.gpa_state = False
                        userstate.general_state = True
                        return

                    forecastCourseID = msg
                    # input user PR level
                    bot.sendMessage(chat_id, "請輸入您的PR值:")
                    userstate.gpa_getGPA_state = True
                    return
                 
                # 輸入通知識別碼
                bot.sendMessage(chat_id, "請輸入要預測的識別碼:",reply_markup=ReplyKeyboardRemove())
                userstate.gpa_myGPA_state = True

                   

            #課程查詢
            if(userstate.search_course_state):

                # msg = 課名
                # @DB involves, 用課名找到識別碼
                if(userstate.search_course_list_state):
                    course_set = Course.objects.filter(cid = msg)
                    if(len(course_set) == 0):
                        bot.sendMessage(chat_id, "找不到該課程!")
                    else:
                        bot.sendMessage(chat_id, "找到結果如下:")
                    target_course = course_set[0]
                    bot.sendMessage(chat_id, "課程識別碼: " + target_course.cid + "\n課程名稱: " + target_course.name + "\n上課時間: " + target_course.time + "\n課程網課號: " + target_course.courseNum) 
                    # bot.sendLocation(chat_id, 25.014038, 121.538184, disable_notification=None)
                    # state release
                    userstate.search_course_state = False
                    userstate.search_course_list_state = False
                    userstate.general_state = True
                    return



                bot.sendMessage(chat_id, "查詢課程相關資訊的服務!請輸入欲查詢的課名:")
                userstate.search_course_list_state = True
                



            if userstate.general_state == True:
                bot.sendMessage(chat_id, '您好,請問您需要什麼服務?', reply_markup=service_keyboard)
Ejemplo n.º 5
0
async def on_chat_message(msg):

    global answerData, lowerFormulas

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

    # 'a' = append, сохраняем в блокноте
    with open('papaz.log', 'a', encoding='utf8') as logFile:
        if content_type != 'text':
            return

        logFile.write('[' + strftime("%Y-%m-%d %H:%M:%S") + '][' +
                      chat_id_str + ' -> bot]: ' + msg['text'] + '\n')
        print('Chat:', content_type, chat_type, chat_id)
        print('Пльзователь ' + chat_id_str + ' написал:\n' +
              msg['text'].lower())
        request = msg['text']  #.lower()

        if request in ('/start', 'hi', 'help', 'привет', 'помощь', 'старт',
                       'start'):
            await bot.sendMessage(chat_id,
                                  answerData['welcome'])  #,reply_markup=rkh)
            logFile.write('[' + strftime("%Y-%m-%d %H:%M:%S") + '][bot -> ' +
                          chat_id_str + ']: ' + answerData['welcome'] + '\n')
            return
        elif request in ("Test1"):
            testAnswers = [
                "Pifagor", 'Gerodot', 'Efklid', 'Arhimed', 'Ahmed', 'Otvet'
            ]
            inline_keyboard = []
            for a in range(len(testAnswers)):
                inline_keyboard.append([
                    InlineKeyboardButton(text=testAnswers[a],
                                         callback_data=testAnswers[a])
                ])
            ikm = InlineKeyboardMarkup(inline_keyboard=inline_keyboard)
            await bot.sendMessage(
                chat_id,
                'Кто из древнегреческих математиков является чемпионом Олимпийских игр в кулачном бою и музыкантом?:',
                reply_markup=ikm)
        elif request in ("Test2"):
            testAnswers = [
                "(m*S)", '(m*a)', '(S/t)', '(a*b)', '(da+da)',
                'Tochno ne otvet'
            ]
            inline_keyboard = []
            for a in range(len(testAnswers)):
                inline_keyboard.append([
                    InlineKeyboardButton(text=testAnswers[a],
                                         callback_data=testAnswers[a])
                ])
            ikm = InlineKeyboardMarkup(inline_keyboard=inline_keyboard)
            await bot.sendMessage(chat_id,
                                  'Выберите  формулы силы',
                                  reply_markup=ikm)
        elif request in answerData['formulas'].keys():
            add = answerData["addsToAnswer"]
            await bot.sendMessage(chat_id, answerData['formulas'][request])
            logFile.write('[' + strftime("%Y-%m-%d %H:%M:%S") + '][bot -> ' +
                          chat_id_str + ']: ' +
                          answerData['formulas'][request] + '\n')
            return
        elif request in lowerFormulas:
            await bot.sendMessage(chat_id, answerData["lowRequest"])
            logFile.write('[' + strftime("%Y-%m-%d %H:%M:%S") + '][bot -> ' +
                          chat_id_str + ']: ' + answerData["lowRequest"] +
                          '\n')
            return
        elif request.lower() in ["тупой"]:
            await bot.sendMessage(chat_id, "Сам ты такой! За шо ты так?")
            logFile.write('[' + strftime("%Y-%m-%d %H:%M:%S") + '][bot -> ' +
                          chat_id_str + ']: ' + "Сам ты такой! За шо ты так?" +
                          '\n')
            return
        else:
            await bot.sendMessage(chat_id, answerData['badRequest'])
Ejemplo n.º 6
0
def basic_keyboard(data, kind):
    buttons = [[
        InlineKeyboardButton(text=d['name'], callback_data=f"{kind}_{d['id']}")
    ] for d in data]
    return InlineKeyboardMarkup(inline_keyboard=buttons)
Ejemplo n.º 7
0
    def on_chat_message(self, msg):
        bot_username = bot.getMe()["username"]
        chat_id = msg['chat']['id']

        print("Msg from %s " % chat_id)  #Channel id has "-". Keep it add to

        if ((config.admin_chat_id == None and config.channel_id == None)
                or chat_id == config.admin_chat_id
                or chat_id == config.channel_id):

            try:
                command = msg['text']
                command = command.split(" ")
            except:
                command = "NoTextHere"
            if len(command) > 1 and type(command) == list:
                if (command[1].find("https://t.me/joinchat/") == -1):
                    temp_list = list()

                    for cmd in command:
                        temp_list.append(cmd.lower())

                    command = temp_list
                    temp_list = None
                else:
                    command[0] = command[0].lower()

            if (command[0][0] == "/"):
                if (len(command) == 1):
                    if (command[0] == '/channels'
                            or command[0] == '/channels@' + bot_username):
                        list_of_channels = "Channels followed:\n\n" + GetChannels(
                        )
                        bot.sendMessage(chat_id, list_of_channels)

                    elif (command[0] == '/setads'
                          or command[0] == '/setads@' + bot_username):
                        ads_block_status = ChangeEnableAds(None)
                        bot.sendMessage(chat_id,
                                        "AdBlock %s" % ads_block_status)

                    elif (command[0] == '/rules'
                          or command[0] == '/rules@' + bot_username):
                        ads_block_list = GetAdsRuleList()
                        bot.sendMessage(
                            chat_id,
                            text="*AdBlock List*:\n\n" + ads_block_list,
                            parse_mode="Markdown",
                            reply_markup=InlineKeyboardMarkup(
                                inline_keyboard=[[
                                    InlineKeyboardButton(
                                        text='Enable', callback_data='enable'),
                                    InlineKeyboardButton(
                                        text='Disable',
                                        callback_data='disable'),
                                ]]))

                    else:
                        bot.sendMessage(chat_id, "Incorrect input")
                else:
                    if command[0] == '/add':
                        new_channel = CheckCorrectly(command[1])
                        if (new_channel != "error"):
                            AddChannel(new_channel)
                            bot.sendMessage(chat_id,
                                            "Successful add %s" % new_channel)
                        else:
                            bot.sendMessage(chat_id,
                                            "Incorrect channel format")

                    elif command[0] == '/del':

                        result = DeleteChannel(command[1])
                        if (result):
                            bot.sendMessage(
                                chat_id, "Successful delete %s" % command[1])
                        else:
                            bot.sendMessage(
                                chat_id,
                                "Channel %s allready unfollowed" % command[1])

                    elif command[0] == '/addrule':
                        input_text = CollectOtherText(command[1:len(command)])
                        print(input_text)
                        AddRuleToList(input_text)
                        bot.sendMessage(chat_id,
                                        "Successful add %s" % input_text)

                    elif command[0] == '/delrule':
                        input_text = CollectOtherText(command[1:len(command)])
                        result = DeleteRule(input_text)
                        if (result):
                            bot.sendMessage(
                                chat_id, "Successful delete %s" % input_text)
                        else:
                            bot.sendMessage(
                                chat_id,
                                "Rule %s allready deleted" % input_text)

        else:
            logging.info("Unverifed chat: %s" % chat_id)
Ejemplo n.º 8
0
def reply(msg):
    msgType, chatType, chatId = telepot.glance(msg)
    name = msg['from']['first_name']
    try:
        text = msg['text']
    except ValueError:
        text = ""

    # Se l'utente non è nel database, inseriscilo
    if not User.exists(lambda u: u.chatId == chatId):
        User(chatId=chatId, status="new")

    user = User.get(chatId=chatId)

    #donazioni
    if text == "/dona":
        bot.sendMessage(chatId, "Ecco qui il mio link PayPal, Grazie mille! \n"
                                "https://www.paypal.me/wapeetyofficial")

    #aiuto

    if text == "/aiuto":
        bot.sendMessage(chatId, "Ecco qui i vari comandi disponibili \n"
                                "/configura - Se non hai ancora configurato il bot \n"
                                "/cancella - Se hai sbagliato a configurare il bot o vuoi cancellare la tua configurazione \n"
                                "/dona - Se dovessi sentirti tanto buono da donare qualcosina (offerta libera) \n"
                                "/aiuto - Per mostrare questo messaggio")

    # Se l'utente ha configurato tutto
    if user.status == "normal":
        if text == "/start":
            bot.sendMessage(chatId, "Bentornato, <b>{0}</b>!\n"
                                    "Da quanto tempo!".format(name), parse_mode="HTML")

        elif text == "/configura":
            bot.sendMessage(chatId, "Non c'è bisogno di configurarmi, hai già fatto tutto!")
        elif text == "/cancella":
            sent = bot.sendMessage(chatId, "Vuoi cancellare i tuoi dati per sempre? (questa azione é irreversibile)")
            keyboard = InlineKeyboardMarkup(inline_keyboard=[[
                InlineKeyboardButton(text="Si", callback_data="del_yes#{0}".format(sent['message_id'])),
                InlineKeyboardButton(text="No", callback_data="del_no#{0}".format(sent['message_id']))
            ]])
            bot.editMessageReplyMarkup((chatId, sent['message_id']), keyboard)


    # Se l'utente deve ancora inserire i dati
    elif user.status == "new":
        if text == "/start":
            bot.sendMessage(chatId, "Benvenuto, <b>{0}</b>!\n"
                                    "Per iniziare, premi /configura.".format(name), parse_mode="HTML")

        elif text == "/configura":
            user.status = "getting_area"
            sent = bot.sendMessage(chatId, "OK! Per iniziare, scegli la tua area di raccolta.", reply_markup=None)
            keyboard = InlineKeyboardMarkup(inline_keyboard=[[
                InlineKeyboardButton(text="Area urbana", callback_data="areaURB#{0}".format(sent['message_id'])),
                InlineKeyboardButton(text="Area industriale", callback_data="areaIND#{0}".format(sent['message_id']))
            ],
            [
                InlineKeyboardButton(text="Area extraurbana", callback_data="areaEXT#{0}".format(sent['message_id']))
            ]])
            bot.editMessageReplyMarkup((chatId, sent['message_id']), keyboard)
Ejemplo n.º 9
0
def checkRelay():
    try:
        cnx = mysql.connector.connect(user=MySQL_username,
                                      password=MySQL_password,
                                      database=MySQL_database)
        cursor = cnx.cursor()
        query = (
            "SELECT id, naam, status_time, notification, arduino, pin, notification_snooze FROM Core_Arduino_Outputs WHERE notification IS NOT NULL AND notification <> '' AND notification_dismiss = 0 AND status = 'ON' "
        )

        logger.printLog(debug, str(query), str(logger.get_linenumber()))
        cursor.execute(query)
        NotificationList = []
        for (id, naam, Time_on, notification, arduino, pin, snooze) in cursor:
            logger.printLog(debug, 'Found Record: %s' % naam,
                            str(logger.get_linenumber()))
            Time = datetime.datetime.now()
            time_delta = (Time - Time_on).total_seconds()
            if (int(time_delta) > int(notification)):
                if snooze is None:
                    logger.printLog(
                        debug,
                        'Add : %s to notification list NOT SNOOZED' % naam,
                        str(logger.get_linenumber()))
                    NotificationList.append([id, naam, arduino, pin])
                else:
                    if snooze < Time:
                        logger.printLog(
                            debug,
                            'Add : %s to notification list SNOOZED' % naam,
                            str(logger.get_linenumber()))
                        NotificationList.append([id, naam, arduino, pin])
    except Exception as e:
        logger.printLog(alert, e, str(logger.get_linenumber()))
        raise
    finally:
        cursor.close()
        cnx.close()

    if len(NotificationList) > 0:
        KeyBoardArray = []
        Message = "Following lights are on"
        global AllLowN
        AllLowN = []
        for Notication in NotificationList:
            text = str(Notication[1])
            callback = NotificationMethod + '|Low|' + str(
                Notication[0]) + ';' + str(Notication[1]) + ';' + str(
                    Notication[2]) + ';' + str(Notication[3])
            KeyBoardArray.append([
                InlineKeyboardButton(text=str(text),
                                     callback_data=str(callback))
            ], )
            AllLowN.append([Notication[0], Notication[2], Notication[3]])
        if len(NotificationList) > 1:
            text = "* Alles uit *"
            callback = NotificationMethod + '|Low|AllLowN'
            KeyBoardArray.append([
                InlineKeyboardButton(text=str(text),
                                     callback_data=str(callback))
            ], )
        text = "* Ignore *"
        callback = NotificationMethod + '|Ignore|'
        KeyBoardArray.append([
            InlineKeyboardButton(text=str(text), callback_data=str(callback))
        ], )
        text = "* Snooze " + str(NotificationSnooze) + "min *"
        callback = NotificationMethod + '|Snooze|'
        KeyBoardArray.append([
            InlineKeyboardButton(text=str(text), callback_data=str(callback))
        ], )

        markup = InlineKeyboardMarkup(inline_keyboard=KeyBoardArray)
        for BotID in BotIDS:
            logger.printLog(debug,
                            "Notification message has been send to " + BotID,
                            str(logger.get_linenumber()))
            bot.sendMessage(int(BotID), Message, reply_markup=markup)

        Time = datetime.datetime.now() + datetime.timedelta(
            seconds=int(TimeBetweenNotification) * 60)
        try:
            cnx = mysql.connector.connect(user=MySQL_username,
                                          password=MySQL_password,
                                          database=MySQL_database)
            cursor = cnx.cursor()
            for relais in AllLowN:
                query = (
                    "UPDATE Core_Arduino_Outputs SET notification_snooze = '" +
                    str(Time) + "' WHERE id=" + str(relais[0]))
                logger.printLog(debug, query, str(logger.get_linenumber()))
                cursor.execute(query)
                cnx.commit()
        except Exception as e:
            logger.printLog(alert, e, str(logger.get_linenumber()))
            raise
        finally:
            cursor.close()
            cnx.close()
Ejemplo n.º 10
0
def Audio(audio, chat_id):
    global spo
    global is_audio

    is_audio = 1
    audi = loc_dir + audio + ".ogg"

    try:
        bot.download_file(audio, audi)
    except telepot.exception.TelegramError:
        sendMessage(
            chat_id,
            "File sent is too big, please send a file lower than 20 MB")
        is_audio = 0
        return

    audio = acrcloud.recognizer(audi)
    is_audio = 0

    try:
        os.remove(audi)
    except FileNotFoundError:
        pass

    if audio['status']['msg'] != "Success":
        sendMessage(chat_id,
                    "Sorry cannot detect the song from audio :(, retry...")
        return

    artist = audio['metadata']['music'][0]['artists'][0]['name']
    track = audio['metadata']['music'][0]['title']
    album = audio['metadata']['music'][0]['album']['name']

    try:
        date = audio['metadata']['music'][0]['release_date']
        album += "_" + date
    except KeyError:
        album += "_"

    try:
        label = audio['metadata']['music'][0]['label']
        album += "_" + label
    except KeyError:
        album += "_"

    try:
        genre = audio['metadata']['music'][0]['genres'][0]['name']
        album += "_" + genre
    except KeyError:
        album += "_"

    if len(album) > 64:
        album = "Infos with too many bytes"

    try:
        url = request(
            "https://api.deezer.com/search/track/?q=" +
            track.replace("#", "") + " + " + artist.replace("#", ""), chat_id,
            True).json()
    except AttributeError:
        return

    try:
        for a in range(url['total'] + 1):
            if url['data'][a]['title'] == track:
                ids = url['data'][a]['link']
                image = url['data'][a]['album']['cover_xl']
                break
    except IndexError:
        try:
            ids = "https://open.spotify.com/track/" + audio['metadata'][
                'music'][0]['external_metadata']['spotify']['track']['id']

            try:
                url = spo.track(ids)
            except:
                spo = spotipy.Spotify(auth=generate_token())

                url = spo.track(ids)

            image = url['album']['images'][0]['url']
        except KeyError:
            pass

        try:
            ids = "https://api.deezer.com/track/" + str(
                audio['metadata']['music'][0]['external_metadata']['deezer']
                ['track']['id'])

            try:
                url = request(ids, chat_id, True).json()
            except AttributeError:
                return

            image = url['album']['cover_xl']
        except KeyError:
            pass

    try:
        sendPhoto(chat_id,
                  image,
                  caption=track + " - " + artist,
                  reply_markup=InlineKeyboardMarkup(inline_keyboard=[[
                      InlineKeyboardButton(text="Download", callback_data=ids),
                      InlineKeyboardButton(text="Info", callback_data=album)
                  ]]))
    except:
        sendMessage(chat_id, "Error :(")
Ejemplo n.º 11
0
def inline(msg, from_id, query_data, query_id):
    if "artist" in query_data:
        message_id = msg['message']['message_id']

        array = []

        if "album" in query_data:
            try:
                url = request(query_data, from_id, True).json()
            except AttributeError:
                return

            array += [[
                InlineKeyboardButton(text=a['title'] + " - " +
                                     a['release_date'].replace("-", "/"),
                                     callback_data=a['link'])
            ] for a in url['data']]

            array.append([
                InlineKeyboardButton(text="BACK 🔙",
                                     callback_data=query_data.split("/")[-2] +
                                     "/" + "artist")
            ])

            bot.editMessageReplyMarkup(
                ((from_id, message_id)),
                reply_markup=InlineKeyboardMarkup(inline_keyboard=array))

        elif "down" in query_data:
            if ans == "2":
                if users[from_id] == 3:
                    bot.answerCallbackQuery(
                        query_id,
                        translate(
                            languag[from_id],
                            "Wait the end and repeat the step, did you think you could download how much songs you wanted? ;)"
                        ),
                        show_alert=True)

                    return
                else:
                    users[from_id] += 1

            bot.answerCallbackQuery(
                query_id, translate(languag[from_id], "Songs are downloading"))

            try:
                url = request(
                    "https://api.deezer.com/artist/" +
                    query_data.split("/")[-4] + "/" +
                    query_data.split("/")[-1], from_id, True).json()
            except AttributeError:
                return

            for a in url['data']:
                Link("https://www.deezer.com/track/" + str(a['id']), from_id,
                     qualit[from_id], msg['message'])

                if ans == "2":
                    users[from_id] += 1

            if ans == "2":
                users[from_id] -= 1

        elif "radio" in query_data or "top" in query_data:
            try:
                url = request(query_data, from_id, True).json()
            except AttributeError:
                return

            array += [[
                InlineKeyboardButton(
                    text=a['artist']['name'] + " - " + a['title'],
                    callback_data="https://www.deezer.com/track/" +
                    str(a['id']))
            ] for a in url['data']]

            array.append([
                InlineKeyboardButton(text="GET ALL ⬇️",
                                     callback_data=query_data.split("/")[-2] +
                                     "/artist/down/" +
                                     query_data.split("/")[-1])
            ])

            array.append([
                InlineKeyboardButton(text="BACK 🔙",
                                     callback_data=query_data.split("/")[-2] +
                                     "/" + "artist")
            ])

            bot.editMessageReplyMarkup(
                ((from_id, message_id)),
                reply_markup=InlineKeyboardMarkup(inline_keyboard=array))

        else:
            link = "https://api.deezer.com/artist/" + query_data.split("/")[-2]

            try:
                url = request(
                    "https://api.deezer.com/artist/" +
                    query_data.split("/")[-2], from_id, True).json()
            except AttributeError:
                return

            bot.editMessageReplyMarkup(
                ((from_id, message_id)),
                reply_markup=InlineKeyboardMarkup(
                    inline_keyboard=[[
                        InlineKeyboardButton(text="TOP 30",
                                             callback_data=link +
                                             "/top?limit=30"),
                        InlineKeyboardButton(text="ALBUMS",
                                             callback_data=link + "/albums")
                    ],
                                     [
                                         InlineKeyboardButton(
                                             text="RADIO",
                                             callback_data=link + "/radio")
                                     ]]))
    else:
        tags = query_data.split("_")

        if tags[0] == "Infos with too many bytes":
            bot.answerCallbackQuery(query_id,
                                    translate(languag[from_id], query_data))

        elif len(tags) == 4:
            bot.answerCallbackQuery(
                query_id,
                text=("Album: %s\nDate: %s\nLabel: %s\nGenre: %s" %
                      (tags[0], tags[1], tags[2], tags[3])),
                show_alert=True)

        else:
            if ans == "2":
                if users[from_id] == 3:
                    bot.answerCallbackQuery(
                        query_id,
                        translate(
                            languag[from_id],
                            "Wait the end and repeat the step, did you think you could download how much songs you wanted? ;)"
                        ),
                        show_alert=True)

                    return
                else:
                    users[from_id] += 1

            bot.answerCallbackQuery(
                query_id, translate(languag[from_id], "Song is downloading"))

            Link(query_data, from_id, qualit[from_id], msg['message'])
Ejemplo n.º 12
0
def Link(link, chat_id, quality, msg):
    global spo
    global del1

    del1 += 1
    done = 0
    links1 = []
    links2 = []
    quali = quality.split("MP3_")[-1]

    if "?" in link:
        link = link.split("?")[0]

    try:
        if "spotify" in link:
            if "track/" in link:
                try:
                    url = spo.track(link)
                except Exception as a:
                    if not "The access token expired" in str(a):
                        sendMessage(chat_id,
                                    "Invalid link ;)",
                                    reply_to_message_id=msg['message_id'])

                        delete(chat_id)
                        return

                    spo = spotipy.Spotify(auth=generate_token())

                    url = spo.track(link)

                try:
                    image1 = url['album']['images'][0]['url']
                except IndexError:
                    image1 = "https://e-cdns-images.dzcdn.net/images/cover/1000x1000-000000-80-0-0.jpg"

                sendPhoto(
                    chat_id,
                    image1,
                    caption=(
                        send_image_track_query %
                        (url['name'], url['album']['artists'][0]['name'],
                         url['album']['name'], url['album']['release_date'])))

                track(link, chat_id, quality)

            elif "album/" in link:
                try:
                    tracks = spo.album(link)
                except Exception as a:
                    if not "The access token expired" in str(a):
                        sendMessage(chat_id,
                                    "Invalid link ;)",
                                    reply_to_message_id=msg['message_id'])

                    delete(chat_id)
                    return

                    spo = spotipy.Spotify(auth=generate_token())

                    tracks = spo.album(link)

                try:
                    image3 = tracks['images'][2]['url']
                    image1 = tracks['images'][0]['url']
                except IndexError:
                    image3 = "https://e-cdns-images.dzcdn.net/images/cover/90x90-000000-80-0-0.jpg"
                    image1 = "https://e-cdns-images.dzcdn.net/images/cover/1000x1000-000000-80-0-0.jpg"

                tot = tracks['total_tracks']
                conn = sqlite3.connect(db_file)
                c = conn.cursor()
                count = 0

                for a in tracks['tracks']['items']:
                    count += a['duration_ms']

                    c.execute(where_query %
                              (a['external_urls']['spotify'], quali))

                    links2.append(a['external_urls']['spotify'])

                    if c.fetchone() != None:
                        links1.append(a['external_urls']['spotify'])

                if (count / 1000) > 40000:
                    sendMessage(
                        chat_id,
                        "If you do this again I will come to your home and I will ddos your ass :)"
                    )
                    delete(chat_id)
                    return

                sendPhoto(
                    chat_id,
                    image1,
                    caption=(send_image_album_query %
                             (tracks['name'], tracks['artists'][0]['name'],
                              tracks['release_date'], tot)))

                tracks = tracks['tracks']

                if tot != 50:
                    for a in range(tot // 50):
                        try:
                            tracks2 = spo.next(tracks)
                        except:
                            spo = spotipy.Spotify(auth=generate_token())

                            tracks2 = spo.next(tracks)

                        for a in tracks2['items']:
                            c.execute(where_query %
                                      (a['external_urls']['spotify'], qualit))

                            links2.append(a['external_urls']['spotify'])

                            if c.fetchone() != None:
                                links1.append(a['external_urls']['spotify'])

                conn.close()

                if len(links1) != tot:
                    z = downloa.download_albumspo(link,
                                                  quality=quality,
                                                  recursive_quality=True,
                                                  recursive_download=True)
                else:
                    for a in links2:
                        track(a, chat_id, quality)

                done = 1

            elif "playlist/" in link:
                musi = link.split("/")

                try:
                    tracks = spo.user_playlist(musi[-3], playlist_id=musi[-1])
                except Exception as a:
                    if not "The access token expired" in str(a):
                        sendMessage(chat_id,
                                    "Invalid link ;)",
                                    reply_to_message_id=msg['message_id'])

                        delete(chat_id)
                        return

                    spo = spotipy.Spotify(auth=generate_token())

                    tracks = spo.user_playlist(musi[-3], playlist_id=musi[-1])

                try:
                    image1 = tracks['images'][0]['url']
                except IndexError:
                    image1 = "https://e-cdns-images.dzcdn.net/images/cover/1000x1000-000000-80-0-0.jpg"

                tot = tracks['tracks']['total']

                if tot > 400:
                    sendMessage(chat_id, "F**k you")
                    delete(chat_id)
                    return

                sendPhoto(chat_id,
                          image1,
                          caption=(send_image_playlist_query %
                                   (tracks['tracks']['items'][0]['added_at'],
                                    tracks['owner']['display_name'], tot)))

                for a in tracks['tracks']['items']:
                    try:
                        track(a['track']['external_urls']['spotify'], chat_id,
                              quality)
                    except KeyError:
                        try:
                            sendMessage(chat_id,
                                        a['track']['name'] + " Not found :(")
                        except KeyError:
                            sendMessage(chat_id, "Error :(")

                tot = tracks['tracks']['total']
                tracks = tracks['tracks']

                if tot != 100:
                    for a in range(tot // 100):
                        try:
                            tracks = spo.next(tracks)
                        except:
                            spo = spotipy.Spotify(auth=generate_token())

                            tracks = spo.next(tracks)
                        for a in tracks['items']:
                            try:
                                track(a['track']['external_urls']['spotify'],
                                      chat_id, quality)
                            except KeyError:
                                try:
                                    sendMessage(
                                        chat_id,
                                        a['track']['name'] + " Not found :(")
                                except KeyError:
                                    sendMessage(chat_id, "Error :(")

                done = 1

            else:
                sendMessage(chat_id,
                            "Sorry :( The bot doesn't support this link")

        elif "deezer" in link:
            if "track/" in link:
                try:
                    url = request(
                        "https://api.deezer.com/track/" + link.split("/")[-1],
                        chat_id, True).json()
                except AttributeError:
                    delete(chat_id)
                    return

                image1 = url['album']['cover_xl']

                if image1 == None:
                    URL = "https://www.deezer.com/track/" + link.split("/")[-1]
                    image1 = request(URL).text

                    image1 = (BeautifulSoup(image1, "html.parser").find(
                        "meta", property="og:image").get("content").replace(
                            "500x500", "90x90"))

                ima = request(image1).content

                if len(ima) == 13:
                    image1 = "https://e-cdns-images.dzcdn.net/images/cover/1000x1000-000000-80-0-0.jpg"

                sendPhoto(
                    chat_id,
                    image1,
                    caption=(
                        send_image_track_query %
                        (url['title'], url['artist']['name'],
                         url['album']['title'], url['album']['release_date'])))

                track(link, chat_id, quality)

            elif "album/" in link:
                try:
                    url = request(
                        "https://api.deezer.com/album/" + link.split("/")[-1],
                        chat_id, True).json()
                except AttributeError:
                    delete(chat_id)
                    return

                if url['duration'] > 40000:
                    sendMessage(
                        chat_id,
                        "If you do this again I will come to your home and I will ddos your ass :)"
                    )
                    delete(chat_id)
                    return

                image1 = url['cover_xl']

                if image1 == None:
                    URL = "https://www.deezer.com/album/" + link.split("/")[-1]
                    image1 = request(URL).text

                    image1 = (BeautifulSoup(image1, "html.parser").find(
                        "img", class_="img_main").get("src").replace(
                            "200x200", "1000x1000"))

                ima = request(image1).content

                if len(ima) == 13:
                    image1 = "https://e-cdns-images.dzcdn.net/images/cover/1000x1000-000000-80-0-0.jpg"

                image3 = image1.replace("1000x1000", "90x90")

                conn = sqlite3.connect(db_file)
                c = conn.cursor()

                for a in url['tracks']['data']:
                    c.execute(where_query % (a['link'], quali))

                    links2.append(a['link'])

                    if c.fetchone() != None:
                        links1.append(a['link'])

                conn.close()

                tot = url['nb_tracks']

                sendPhoto(chat_id,
                          image1,
                          caption=(send_image_album_query %
                                   (url['title'], url['artist']['name'],
                                    url['release_date'], tot)))

                if len(links1) != tot:
                    z = downloa.download_albumdee(link,
                                                  quality=quality,
                                                  recursive_quality=True,
                                                  recursive_download=True)
                else:
                    for a in links2:
                        track(a, chat_id, quality)

                done = 1

            elif "playlist/" in link:
                try:
                    url = request(
                        "https://api.deezer.com/playlist/" +
                        link.split("/")[-1], chat_id, True).json()
                except AttributeError:
                    delete(chat_id)
                    return

                tot = url['nb_tracks']

                if tot > 400:
                    sendMessage(chat_id, "F**k you")
                    delete(chat_id)
                    return

                sendPhoto(
                    chat_id,
                    url['picture_xl'],
                    caption=(
                        send_image_playlist_query %
                        (url['creation_date'], url['creator']['name'], tot)))

                for a in url['tracks']['data']:
                    track(a['link'], chat_id, quality)

                done = 1

            elif "artist/" in link:
                link = "https://api.deezer.com/artist/" + link.split("/")[-1]

                try:
                    url = request(link, chat_id, True).json()
                except AttributeError:
                    delete(chat_id)
                    return

                sendPhoto(
                    chat_id,
                    url['picture_xl'],
                    caption=("Artist:" + url['name'] + "\nAlbum numbers:" +
                             str(url['nb_album']) + "\nFans on Deezer:" +
                             str(url['nb_fan'])),
                    reply_markup=InlineKeyboardMarkup(
                        inline_keyboard=[[
                            InlineKeyboardButton(text="TOP 30",
                                                 callback_data=link +
                                                 "/top?limit=30"),
                            InlineKeyboardButton(
                                text="ALBUMS", callback_data=link + "/albums")
                        ],
                                         [
                                             InlineKeyboardButton(
                                                 text="RADIO",
                                                 callback_data=link + "/radio")
                                         ]]))

            else:
                sendMessage(chat_id,
                            "Sorry :( The bot doesn't support this link")

        else:
            sendMessage(chat_id, "Sorry :( The bot doesn't support this link")

        try:
            image3 = request(image3).content

            for a in range(len(z)):
                sendAudio(chat_id, z[a], links2[a], image3)
        except NameError:
            pass

    except deezloader.exceptions.QuotaExceeded:
        sendMessage(chat_id, "Please send the link again :(")

    except deezloader.exceptions.AlbumNotFound:
        sendMessage(chat_id, "Album didn't find on Deezer :(")
        sendMessage(
            chat_id,
            "Try to search it throught inline mode or search the link on Deezer"
        )

    except Exception as a:
        logging.warning(a)
        logging.warning(link)
        sendMessage(
            chat_id,
            "OPS :( Something went wrong please contact @An0nimia to explain the issue, if this happens again"
        )

    if done == 1:
        sendMessage(chat_id,
                    "FINISHED :) Rate me here https://t.me/BotsArchive/298",
                    reply_to_message_id=msg['message_id'],
                    reply_markup=InlineKeyboardMarkup(inline_keyboard=[[
                        InlineKeyboardButton(
                            text="SHARE",
                            url="tg://msg?text=Start @" + bot_name +
                            " for download all the songs which you want ;)")
                    ]]))

    delete(chat_id)
Ejemplo n.º 13
0
def start(msg):
    global free

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

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

    pprint(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, 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.jpg", "rb"),
                      caption="Welcome to @" + bot_name +
                      "\nPress '/' to get commands list")
        except FileNotFoundError:
            pass

        sendMessage(
            chat_id,
            "Press for search songs or albums or artists\nP.S. Remember you can do this digiting @ in your keyboard and select "
            + 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="artist:"),
                    InlineKeyboardButton(
                        text="Search by album",
                        switch_inline_query_current_chat="album:")
                ],
                                 [
                                     InlineKeyboardButton(
                                         text="Global search",
                                         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, "Now the language is english")
        else:
            languag[chat_id] = 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: " +
                    qualit[chat_id],
                    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,
                    "Songs will be downloaded in " + msg['text'] + " quality",
                    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\nName: @%s\nCreator: @%s\nDonation: %s\nForum: %s\nUsers: %s\nTotal downloads: %s"
            % (version, bot_name, creator, donation_link, group_link,
               statisc(chat_id, "USERS"), statisc(chat_id, "TRACKS")))

    elif content_type == "text" and chat_id == 560950095 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":
        try:
            msg['entities']

            if ans == "2" and users[chat_id] == 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] += 1

                Thread(target=Link,
                       args=(msg['text'].replace("'", ""), chat_id,
                             qualit[chat_id], msg)).start()
        except KeyError:
            sendMessage(
                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'])
                    ]
                ]))
Ejemplo n.º 14
0
class Lover(telepot.helper.ChatHandler):
    keyboard = InlineKeyboardMarkup(inline_keyboard=[
        [  #<-- Menu awal
            InlineKeyboardButton(text='Beri pakan', callback_data='pakan'),
            InlineKeyboardButton(text='Pengaturan', callback_data='setting')
        ],
        [
            InlineKeyboardButton(text='um ...', callback_data='no'),
            InlineKeyboardButton(text='keluar', callback_data='keluar')
        ]
    ])
    keyboard1 = InlineKeyboardMarkup(inline_keyboard=[
        [  #<-- Terusan Pengaturan dari Menu Awal
            InlineKeyboardButton(text='Set penjadwalan pemberian pakan?',
                                 callback_data='waktu')
        ],
        [
            InlineKeyboardButton(text='Set dosis pemberian pakan?',
                                 callback_data='dosis')
        ]
    ])
    keyboard2 = InlineKeyboardMarkup(inline_keyboard=[
        [
            InlineKeyboardButton(text='Kolam 1', callback_data='pknk1'),
            InlineKeyboardButton(text='Kolam 2', callback_data='pknk2')
        ],
        [
            InlineKeyboardButton(text='Kolam 3', callback_data='pknk3'),
            InlineKeyboardButton(text='Semua Kolam', callback_data='pknkAll')
        ], [InlineKeyboardButton(text='Kembali', callback_data='kembali')]
    ])
    keyboard3 = InlineKeyboardMarkup(inline_keyboard=[
        [  #<-- Terusan Pengaturan-Waktu dari Menu Awal
            InlineKeyboardButton(text='Kolam 1', callback_data='wkolam1'),
            InlineKeyboardButton(text='Kolam 2', callback_data='wkolam2')
        ],
        [
            InlineKeyboardButton(text='Kolam 3', callback_data='wkolam3'),
            InlineKeyboardButton(text='Semua Kolam', callback_data='wkolamAll')
        ],
        [InlineKeyboardButton(text='Kembali', callback_data='kembali')]
    ])
    keyboard4 = InlineKeyboardMarkup(inline_keyboard=[
        [  #-- Terusan Pengaturan-Takaran dari Menu Awal
            InlineKeyboardButton(text='Kolam 1', callback_data='dkolam1'),
            InlineKeyboardButton(text='Kolam 2', callback_data='dkolam2')
        ],
        [
            InlineKeyboardButton(text='Kolam 3', callback_data='dkolam3'),
            InlineKeyboardButton(text='Semua Kolam', callback_data='dkolamAll')
        ],
        [InlineKeyboardButton(text='Kembali', callback_data='kembali')]
    ])

    def __init__(self, *args, **kwargs):
        super(Lover, self).__init__(*args, **kwargs)

        # Retrieve from database
        global propose_records
        if self.id in propose_records:
            self._edit_msg_ident = propose_records[self.id]
            self._editor = telepot.helper.Editor(
                self.bot,
                self._edit_msg_ident) if self._edit_msg_ident else None
        else:
            self._edit_msg_ident = None
            self._editor = None

    def _propose(self):
        sent = self.sender.sendMessage('Apa yang bisa saya bantu?',
                                       reply_markup=self.keyboard)
        self._editor = telepot.helper.Editor(self.bot, sent)
        self._edit_msg_ident = telepot.message_identifier(sent)

    """
    def _propose_time(self):
        current_time = time.strftime("%H:%M", t)
        (h, m) = current_time.split(':')
        result = int(h) * 3600 + int(m) * 60
        
        (h, m) = setTime1.split(':')
        timeklm1 = int(h) * 3600 + int(m) * 60
        
        (h, m) = setTime2.split(':')
        timeklm2 = int(h) * 3600 + int(m) * 60
        
        (h, m) = setTime3.split(':')
        timeklm3 = int(h) * 3600 + int(m) * 60
    """

    def _cancel_last(self):
        if self._editor:
            self._editor.editMessageReplyMarkup(reply_markup=None)
            self._editor = None
            self._edit_msg_ident = None

    def on_chat_message(self, msg):
        if msg['from']['id'] != CHATID:
            bot.sendMessage(chat_id,
                            "Maaf ini adalah bot pribadi. Akses ditolak!")
            self.close()
        self._cancel_last()
        self._propose()
        '''
        command = msg['text']
        if (command == '/hi'):
            bot.sendMessage(chat_id, "Hi")
        '''

    def on_callback_query(self, msg):
        query_id, from_id, query_data = telepot.glance(msg,
                                                       flavor='callback_query')

        if query_data == 'keluar':
            self._cancel_last()
            self.sender.sendMessage('Terima kasih! \nBye..')
            self.close()

        # == Setting ==
        elif query_data == 'setting':
            self.bot.answerCallbackQuery(query_id,
                                         text='Ok. Pertanyaan berikutnya...')
            self._cancel_last()
            sent = self.sender.sendMessage('Apa yang ingin anda atur?',
                                           reply_markup=self.keyboard1)
            self._editor = telepot.helper.Editor(self.bot, sent)
            self._edit_msg_ident = telepot.message_identifier(sent)

        elif query_data == 'waktu':
            self.bot.answerCallbackQuery(query_id,
                                         text='Ok. Pertanyaan berikutnya...')
            self._cancel_last()
            sent = self.sender.sendMessage(
                'Kolam mana yang ingin anda atur penjadwalan pakannya?',
                reply_markup=self.keyboard3)
            self._editor = telepot.helper.Editor(self.bot, sent)
            self._edit_msg_ident = telepot.message_identifier(sent)

        elif query_data == 'dosis':
            self.bot.answerCallbackQuery(query_id,
                                         text='Ok. Pertanyaan berikutnya...')
            self._cancel_last()
            sent = self.sender.sendMessage(
                'Kolam mana yang ingin anda atur dosis pakannya?',
                reply_markup=self.keyboard4)
            self._editor = telepot.helper.Editor(self.bot, sent)
            self._edit_msg_ident = telepot.message_identifier(sent)

        # ==pemberian pakan==
        elif query_data == 'pakan':
            self.bot.answerCallbackQuery(query_id,
                                         text='Ok. Pertanyaan berikutnya...')
            self._cancel_last()
            sent = self.sender.sendMessage(
                'Kolam mana yang ingin anda beri pakan?',
                reply_markup=self.keyboard2)
            self._editor = telepot.helper.Editor(self.bot, sent)
            self._edit_msg_ident = telepot.message_identifier(sent)

        elif query_data == 'pknk1':
            if setTime1 == 'null':
                self.bot.answerCallbackQuery(
                    query_id,
                    text='Ok. Pemberian pakan pada kolam 1 akan dilakukan...')
                self._cancel_last()
                #!! kasi pakan, kamera jalan,
                stat1 = 1
                self.sender.sendMessage(
                    'Pemberian pakan pada kolam 1 telah selesai \nketikkan perintah /dokumentasi untuk mendapat rekaman video..'
                )
                self.close()
            else:
                if stat1 == 0:
                    self.bot.answerCallbackQuery(query_id,
                                                 text='Peringatan !!!')
                    self._cancel_last()
                    self.sender.sendMessage(
                        'Pemberian pakan pada kolam 1 Telah dijadwlkan pada pukul'
                        + setTime1 +
                        '\nketikkan perintah /force1 untuk memberikan pakan sekarang juga..'
                    )
                    self.close()

        else:
            self.bot.answerCallbackQuery(
                query_id, text='Ok. Tapi aku akan terus bertanya.')
            self._cancel_last()
            self._propose()

    def on__idle(self, event):
        self.sender.sendMessage(
            'Saya tahu Anda mungkin perlu sedikit waktu. Aku akan selalu di sini untukmu.'
        )
        self._cancel_last()
        self.close()

    def on_close(self, ex):
        # Save to database
        global propose_records
        propose_records[self.id] = (self._edit_msg_ident)
Ejemplo n.º 15
0
async def on_callback_query(user_id, msg_idf, bot, data, **Cwargs):
    if data[:2] == "ch":
        u_id_count = int(data[2:3])
        callback4okacc = data[:u_id_count + 3] + 'oa' + data[u_id_count + 5:]
        callback4noacc = data[:u_id_count + 3] + 'na' + data[u_id_count + 5:]
        callback4okrefused = data[:u_id_count + 3] + 'or' + data[u_id_count + 5:]
        callback4norefused = data[:u_id_count + 3] + 'nr' + data[u_id_count + 5:]
        Inline_markup4charge = InlineKeyboardMarkup(inline_keyboard=[
                                [dict(text = "تایید", callback_data = data[:u_id_count + 3] + 'ok' + data[u_id_count + 5:]),
                                InlineKeyboardButton(text = "رد", callback_data = data[:u_id_count + 3] + 'no' + data[u_id_count + 5:])]])
        Inline_markup4chargeok =  InlineKeyboardMarkup(inline_keyboard=[
                                 [dict(text = "بله", callback_data = callback4okacc),
                                 InlineKeyboardButton(text = "خیر", callback_data = callback4okrefused)]
                                 ])
        Inline_markup4chargeno = InlineKeyboardMarkup(inline_keyboard=[
            [dict(text = "بله", callback_data = callback4noacc),
            InlineKeyboardButton(text = "خیر", callback_data = callback4norefused)]
        ])

        if user_id in my_user_ids:
            data = data[3:]

            if data[u_id_count:u_id_count + 2] == "ok":
                try:
                    await bot.editMessageText(msg_idf, MessageTexts.are_u_sure_ok, reply_markup = Inline_markup4chargeok)
                except:
                    pass
            elif data[u_id_count:u_id_count + 2] == "no":
                try:
                    await bot.editMessageText(msg_idf, MessageTexts.are_u_sure_no, reply_markup = Inline_markup4chargeno)
                except:
                    pass
            elif data[u_id_count:u_id_count + 2] == "oa":
                print("in oa: ", data[u_id_count + 4:])
                await db4takjoy("charge_bot", bot_id = data[u_id_count + 4:], day = "30")
                Date_bot[data[u_id_count + 4:]] += timedelta(days = 30)
                print("Date_bot[data[u_id_count+3:]] :", Date_bot[data[u_id_count+4:]])
                await bot.editMessageText(msg_idf, MessageTexts.thirth_days_adding.format(day = str((Date_bot[data[u_id_count+4:]] - datetime.now()).days)))
                for u_id in my_user_ids:
                    await bot.sendMessage(u_id, MessageTexts.thirth_days_adding.format(day = str((Date_bot[data[u_id_count+4:]] - datetime.now()).days)))
            elif data[u_id_count:u_id_count+2] == "or" or data[u_id_count:u_id_count+2] == "nr":
                try:
                    await bot.editMessageText(msg_idf, MessageTexts.bill4bot_charge.format(bot = data[u_id_count+4:]), reply_markup = Inline_markup4charge)
                except:
                    pass
            elif data[u_id_count:u_id_count + 2] == "na":
                bot_takjoy = telepot.aio.Bot(dic4charge_bot_id2token[data[u_id_count + 2:]])
                try:
                    await bot_takjoy.sendMessage(data[:u_id_count], billnotaccepted)
                    await bot.editMessageText(msg_idf, billrefusion.format(bot = data[u_id_count + 4:]))
                except:
                    pass
    elif data[:2] == "ct":
        data = data[2:]
        if data == "_cancelled":
            try:
                await bot.editMessageText(msg_idf, MessageTexts.Tokens_not_changed)
            except:
                pass
        else:
            try:
                await bot.editMessageText(msg_idf, MessageTexts.token_changing.format(bot = data))
                await bot.sendMessage(user_id, MessageTexts.insert_changed_Token, reply_markup = markup4change_token)
                MessageTexts.give_token[user_id] = "token4change"
                MessageTexts.save_token[user_id] = data
            except:
                pass
Ejemplo n.º 16
0
def handle(msg):

    chat_id = msg['chat']['id']
    command = msg['text']

    logger.printLog(debug, 'Got command: %s' % command,
                    str(logger.get_linenumber()))
    logger.printLog(debug, 'Got chatID from : %s' % chat_id,
                    str(logger.get_linenumber()))

    if str(chat_id) in BotIDS:
        if command == '/status':
            try:
                cnx = mysql.connector.connect(user=MySQL_username,
                                              password=MySQL_password,
                                              database=MySQL_database)
                cursor = cnx.cursor()
                query = (
                    "SELECT naam, arduino, pin FROM Core_Arduino_Outputs WHERE Status = 'ON' AND telegram = '1'"
                )
                logger.printLog(debug, str(query),
                                str(logger.get_linenumber()))
                cursor.execute(query)
                NotificationList = []
                for (naam, arduino, pin) in cursor:
                    NotificationList.append([naam, arduino, pin])
            except Exception as e:
                logger.printLog(alert, e, str(logger.get_linenumber()))
                raise
            finally:
                cursor.close()
                cnx.close()

            KeyBoardArray = []
            if len(NotificationList) > 0:
                Message = "Following lights are on"
            else:
                Message = "No lights are on!"
            global AllLow
            AllLow = []
            for Notication in NotificationList:
                text = str(Notication[0])
                callback = NotificationMethod + '|Low|;' + str(
                    Notication[0]) + ';' + str(Notication[1]) + ';' + str(
                        Notication[2])
                KeyBoardArray.append([
                    InlineKeyboardButton(text=str(text),
                                         callback_data=str(callback))
                ], )
                AllLow.append([Notication[1], Notication[2]])
            if len(NotificationList) > 1:
                text = "* Alles uit *"
                callback = NotificationMethod + '|Low|AllLow'
                KeyBoardArray.append([
                    InlineKeyboardButton(text=str(text),
                                         callback_data=str(callback))
                ], )

            markup = InlineKeyboardMarkup(inline_keyboard=KeyBoardArray)

            logger.printLog(debug, "status has been send to " + str(chat_id),
                            str(logger.get_linenumber()))
            bot.sendMessage(chat_id, Message, reply_markup=markup)

    elif command == '/enroll':
        hide_keyboard = {'hide_keyboard': True}
        text = 'Give this ID to you iRulez Administrator: ' + str(chat_id)
        logger.printLog(debug, "Enrollment has been send to " + str(chat_id),
                        str(logger.get_linenumber()))
        bot.sendMessage(chat_id, text, reply_markup=hide_keyboard)
Ejemplo n.º 17
0
async def start_control(chat_id, Intrance, content_type, **fargs):
    bot = fargs["_bot"]
    if chat_id not in MessageTexts.give_token:
        MessageTexts.give_token[chat_id] = 1
    
    if content_type == 'text':
        if Intrance == 'راهنمایی':
            try:
                await bot.sendMessage(chat_id, MessageTexts.robot_presentation + MessageTexts.robot_presentation2 + MessageTexts.robot_presentation3, reply_markup=markup)        
            except:
                pass
        elif Intrance == 'پشتیبانی':
            try:
                await bot.sendMessage(chat_id, MessageTexts.Guidance, reply_markup = markup)
            except:
                pass

        elif Intrance == "تغییر توکن":
            if str(chat_id) not in dict4bot_ids4users:
                try:
                    await bot.sendMessage(chat_id, no_bot)
                except:
                    pass
            else:
                try:
                    Inline_markup4bot_ids = func_Inline_markup(*dict4bot_ids4users[str(chat_id)])
                    await bot.sendMessage(chat_id, witch_bot, reply_markup = InlineKeyboardMarkup(inline_keyboard = Inline_markup4bot_ids))
                except:
                    pass
        elif MessageTexts.give_token[chat_id] == 1:
            await handle(chat_id, Intrance, **fargs)

        elif MessageTexts.give_token[chat_id] == 3:
            await change_token(chat_id, Intrance)
            
        elif MessageTexts.give_token[chat_id] == "token4change":
            if Intrance == 'انصراف':
                try:
                    await bot.sendMessage(chat_id, MessageTexts.Tokens_not_changed, reply_markup = markup)
                    del MessageTexts.give_token[chat_id]
                except:
                    pass
            else:
                try:
                    temp_bot = telepot.aio.Bot(Intrance)
                    my_bot_intrance = await temp_bot.getMe()
                except:
                    my_bot_intrance = None
                if my_bot_intrance and my_bot_intrance["username"] == MessageTexts.save_token[chat_id]:
                    del MessageTexts.give_token[chat_id]
                    await db4takjoy("chang_token", new_token = Intrance, bot_id = my_bot_intrance["username"])
                    try:
                        await bot.sendMessage(chat_id, MessageTexts.Token_changed.format(bot = my_bot_intrance["username"]))
                        ex_token = dic4charge_bot_id2token[my_bot_intrance["username"]]
                        dic4charge_bot_id2token[my_bot_intrance["username"]] = Intrance
                        e_num = dict_token2e_num[ex_token]
                        del dict_token2e_num[ex_token]
                        dict_token2e_num[Intrance] = e_num
                        UNT_Dict[e_num][1] = Intrance
                        del user_id4owner[ex_token]
                        user_id_owner = str(chat_id) + Intrance
                        user_id4owner[Intrance] = user_id_owner
                        ex_use_id_owner = str(chat_id) + ex_token
                        temp_seller_dict = seller_dict[ex_use_id_owner]
                        seller_dict[user_id_owner] = temp_seller_dict
                        print("dic_user_id[e_num] is: ", dic_user_id[e_num])
                        if e_num in dic_user_id:
                            for u_id_customer in dic_user_id[e_num]:
                                for i in range(0, len(list4customer_chars) - 1):
                                    if u_id_customer != "None":
                                        my_temp = list4customer_chars[i][str(u_id_customer) + ex_token]
                                        del list4customer_chars[i][str(u_id_customer) + ex_token]
                                        list4customer_chars[i][str(u_id_customer) + Intrance] = my_temp
                    except:
                        pass
                else:
                    try:
                        await bot.sendMessage(chat_id, MessageTexts.Token_is_not_correct)
                    except:
                        pass
Ejemplo n.º 18
0
def on_callback_query(msg):
    query_id, from_id, query_data = telepot.glance(msg,
                                                   flavor='callback_query')
    edited = (from_id, msg['message']['message_id'])
    try:

        file = open("__pycache__/" + str(from_id) + ".json", "r")
        json_data = json.load(file)

        if (query_data == str(1)):

            lista = json_data['feedback'][int(query_data) - 1]
            autore = lista['author_name']
            valutazione = str(lista['rating'])
            commento = lista['text']
            feedback = 'Autore: ' + autore + '\nValutazione: ' +\
                valutazione + '\nFeedback: ' + commento

            keyboard = InlineKeyboardMarkup(
                inline_keyboard=[[dict(text='Avanti', callback_data=2)]])

            bot.editMessageText(edited, feedback, reply_markup=keyboard)

        if (query_data == str(2)):
            keyboard = InlineKeyboardMarkup(inline_keyboard=[[
                dict(text='Indietro', callback_data=1),
                dict(text='Avanti', callback_data=3)
            ]])

            lista = json_data['feedback'][int(query_data) - 1]
            autore = lista['author_name']
            valutazione = str(lista['rating'])
            commento = lista['text']
            feedback = 'Autore: ' + autore + '\nValutazione: ' +\
                valutazione + '\nFeedback: ' + commento

            bot.editMessageText(edited, feedback, reply_markup=keyboard)

        if (query_data == str(3)):
            keyboard = InlineKeyboardMarkup(inline_keyboard=[[
                dict(text='Indietro', callback_data=2),
                dict(text='Avanti', callback_data=4)
            ]])

            lista = json_data['feedback'][int(query_data) - 1]
            autore = lista['author_name']
            valutazione = str(lista['rating'])
            commento = lista['text']
            feedback = 'Autore: ' + autore + '\nValutazione: ' +\
                valutazione + '\nFeedback: ' + commento

            bot.editMessageText(edited, feedback, reply_markup=keyboard)

        if (query_data == str(4)):
            keyboard = InlineKeyboardMarkup(inline_keyboard=[[
                dict(text='Indietro', callback_data=3),
                dict(text='Avanti', callback_data=5)
            ]])

            lista = json_data['feedback'][int(query_data) - 1]
            autore = lista['author_name']
            valutazione = str(lista['rating'])
            commento = lista['text']
            feedback = 'Autore: ' + autore + '\nValutazione: ' +\
                valutazione + '\nFeedback: ' + commento

            bot.editMessageText(edited, feedback, reply_markup=keyboard)

        if (query_data == str(5)):
            keyboard = InlineKeyboardMarkup(inline_keyboard=[[
                dict(text='Indietro', callback_data=4),
                dict(text='Fine', callback_data=6)
            ]])

            lista = json_data['feedback'][int(query_data) - 1]
            autore = lista['author_name']
            valutazione = str(lista['rating'])
            commento = lista['text']
            feedback = 'Autore: ' + autore + '\nValutazione: ' +\
                valutazione + '\nFeedback: ' + commento

            bot.editMessageText(edited, feedback, reply_markup=keyboard)

        if (query_data == str(6)):
            bot.editMessageText(edited, 'Fine')

            keyboard = InlineKeyboardMarkup(inline_keyboard=[[
                dict(text='Visualizza feedback di Google', callback_data=1)
            ]])
            bot.editMessageText(edited,
                                "Hai bisogno di aiuto?",
                                reply_markup=keyboard)

    except Exception as e:
        print(e)
Ejemplo n.º 19
0
def composer_keyboard(composers):
    buttons = [[
        InlineKeyboardButton(text=f"{c['lastname']}, {c['firstname']}",
                             callback_data=f"composer_{c['id']}")
    ] for c in composers]
    return InlineKeyboardMarkup(inline_keyboard=buttons)
Ejemplo n.º 20
0
def on_chat_message(msg):
    print(msg)
    global step
    global emailandtelegr
    global is_premium
    global updating_files

    type = msg['chat']['type']

    #if type == "private":
    #    pass
    #    # message from msg['chat']['first_name']
    #elif type == "group":
    #    pass
    #elif type == "supergroup":
    #    pass
    # elif type == "channel":
    #    pass
    #else:
    #    return

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

    # message from msg['chat']['title']

    check_shutdown_file(True, chat_id)

    if updating_files:
        send(
            chat_id,
            "Hi, I'm updating all daily files, I will be available in a few seconds/one minute"
        )
        return

    res = mybot_user.check_new_id("alerts.txt", msg["from"]["first_name"],
                                  chat_id)

    markup = on_settings_msg(chat_id)

    mybot.sendMessage(chat_id, 'Choose your settings', reply_markup=markup)

    if res != None:
        send(chat_id, res)

    if content_type == 'text':
        name = msg["from"]["first_name"]
        text = msg['text']

        # available commands
        if text == '/help':
            str_to_send = 'Hi %s, ' % name

            send(chat_id, str_to_send)

            step = 1

        elif text == '/start':
            markup = on_start_msg(chat_id)

            mybot.sendMessage(chat_id,
                              'Select one crypto',
                              reply_markup=markup)

            step = 1  # in case the user input /sendalert and then start, step is always 2,
            # so if he then inputs random text the bot will say email not valid

        elif text == '/settings':  # manually open settings keyboard
            markup = on_settings_msg(chat_id)

            mybot.sendMessage(chat_id,
                              'Choose your settings',
                              reply_markup=markup)
        elif text == "/refresh":
            refresh_files()

        elif text == '₿📈 GET CRYPTO PRICES 🤑':
            markup = on_start_msg(chat_id)

            mybot.sendMessage(chat_id,
                              'Select one crypto',
                              reply_markup=markup)

        elif text == 'ADD 💶 OR REMOVE 💸 CRYPTO':
            markup = ReplyKeyboardMarkup(keyboard=[
                [
                    KeyboardButton(text='💰 ADD 💰'),
                    KeyboardButton(text='💸 REMOVE 💸')
                ],
                [KeyboardButton(text='❌ BACK ❌')],
            ])
            mybot.sendMessage(chat_id,
                              'Do you want to ADD or REMOVE?',
                              reply_markup=markup)

        elif text == '✉️ CHANGE ALERT TYPE ⏰':
            with open("alerts.txt", "r") as file:
                alert_dict = json.loads(file.read())

            pers_alert = alert_dict[str(chat_id)]

            if pers_alert[0].split("-")[0] == "premium":
                is_premium = True
                markup = ReplyKeyboardMarkup(keyboard=[
                    [
                        KeyboardButton(text='📧 EMAIL 📧'),
                        KeyboardButton(text='📧 EMAIL AND TELEGRAM 📱'),
                        KeyboardButton(text='📱 TELEGRAM 📱'),
                        KeyboardButton(text='💤 NO ALERT 💤')
                    ],
                    [KeyboardButton(text='❌ BACK ❌')],
                ])
                mybot.sendMessage(chat_id,
                                  'Select the type of alert',
                                  reply_markup=markup)
            else:
                is_premium = False

                markup = ReplyKeyboardMarkup(keyboard=[
                    [
                        KeyboardButton(text='📱 TELEGRAM 📱'),
                        KeyboardButton(text='💤 NO ALERT 💤')
                    ],
                    [KeyboardButton(text='❌ BACK ❌')],
                ])
                mybot.sendMessage(chat_id,
                                  'Select the type of alert',
                                  reply_markup=markup)

        elif text == '❌ BACK ❌':
            pass

        elif text == '📧 EMAIL 📧' or text == '📧 EMAIL AND TELEGRAM 📱':
            send(chat_id, "Ok, insert the email")

            if text == "EMAIL":
                emailandtelegr = False
            else:
                emailandtelegr = True

            step = 3

        elif text == '📱 TELEGRAM 📱':

            with open("alerts.txt", "r") as file:
                alert_dict = json.loads(file.read())

            if alert_dict[str(chat_id)][0].split("-")[1] != "telegram":
                if is_premium == True:
                    if "email" in alert_dict[str(chat_id)][
                            0] or "both" in alert_dict[str(chat_id)][0]:
                        alert_dict[str(chat_id)][1] = ""

                    alert_dict[str(chat_id)][0] = "premium-telegram"
                else:
                    if "email" in alert_dict[str(chat_id)][
                            0] or "both" in alert_dict[str(chat_id)][0]:
                        alert_dict[str(chat_id)][1] = ""

                    alert_dict[str(chat_id)][0] = "normal-telegram"

                with open("alerts.txt", "w") as file:
                    json.dump(alert_dict, file)

                start_new_thread(mydrive.delete_file, ("alerts.txt", None))
                start_new_thread(mydrive.upload_file_to_root_dir,
                                 ("alerts.txt", ))

                send(chat_id, "Alert state successfully changed")
            else:
                send(chat_id, "Alert state was already set to 'telegram'")

        elif text == '💤 NO ALERT 💤':

            with open("alerts.txt", "r") as file:
                alert_dict = json.loads(file.read())

            if alert_dict[str(chat_id)][0].split("-")[1] != "none":
                if is_premium == True:
                    if "email" in alert_dict[str(chat_id)][
                            0] or "both" in alert_dict[str(chat_id)][0]:
                        alert_dict[str(chat_id)][1] = ""

                    alert_dict[str(chat_id)][0] = "premium-none"
                else:
                    if "email" in alert_dict[str(chat_id)][
                            0] or "both" in alert_dict[str(chat_id)][0]:
                        alert_dict[str(chat_id)][1] = ""

                    alert_dict[str(chat_id)][0] = "normal-none"

                with open("alerts.txt", "w") as file:
                    json.dump(alert_dict, file)

                send(chat_id, "Alert state successfully changed")

                start_new_thread(mydrive.delete_file, ("alerts.txt", None))
                start_new_thread(mydrive.upload_file_to_root_dir,
                                 ("alerts.txt", ))
            else:
                send(chat_id, "Alert state was already set to 'no alerts'")

        elif text == '🗣️ GIVE SOME ADVICE 📖':
            send(chat_id,
                 "Hi, you can give us advice by typing '/advice your_advice'")

        elif text == '🔥 GET PREMIUM VERSION 🔥':
            send(chat_id, "Sorry, Premium Version not developed yet")

        elif "/advice" in text:
            if text.split("/advice")[1] != "":
                with open("advices.txt", "r") as file:
                    advices_dict = json.loads(file.read())

                if str(chat_id) not in advices_dict:
                    advices_dict.setdefault(str(chat_id), [])

                advices_dict[str(chat_id)].append(text.split("/advice")[1])

                with open("advices.txt", "w") as file:
                    json.dump(advices_dict, file)

                send(chat_id, "Advice saved")

                start_new_thread(mydrive.delete_file, ("advices.txt", None))
                start_new_thread(mydrive.upload_file_to_root_dir,
                                 ("advices.txt", ))

                mybot_tasks.send_email_alert(mybot_tasks.myemail_data()[0],
                                             mybot_tasks.myemail_data()[1],
                                             "New", "Advice on cryptos-bot",
                                             text.split("/advice")[1],
                                             "*****@*****.**", True)

            else:
                send(chat_id, "Sorry, invalid advice")

        elif step == 3:
            step = 1

            new_email = text

            if mybot_user.check_real_email(new_email, chat_id) == False:
                send(chat_id, "Sorry, you have inserted an invalid email")
            else:

                with open("alerts.txt", "r") as file:
                    alert_dict = json.loads(file.read())

                if "email" in alert_dict[str(
                        chat_id)][0] or "both" in alert_dict[str(chat_id)][0]:
                    alert_dict[str(chat_id)][1] = new_email
                else:
                    alert_dict[str(chat_id)].append(new_email)

                if emailandtelegr == False:
                    alert_dict[str(chat_id)][0] = "premium-email"
                else:
                    alert_dict[str(chat_id)][0] = "premium-both"

                with open("alerts.txt", "w") as file:
                    json.dump(alert_dict, file)

                send(chat_id,
                     "Email successfully added and alert state changed")

                start_new_thread(mydrive.delete_file, ("alerts.txt", None))
                start_new_thread(mydrive.upload_file_to_root_dir,
                                 ("alerts.txt", ))

        elif text == '💸 REMOVE 💸':
            with open("personalcryptos.txt", "r") as file:
                pers_cryptos = json.loads(file.read())

            cryptos = pers_cryptos[str(chat_id)]

            markup = InlineKeyboardMarkup(inline_keyboard=[[
                InlineKeyboardButton(text=f'{str(crypto).upper()}',
                                     callback_data=f'remove/{crypto}')
            ] for crypto in cryptos])

            mybot.sendMessage(chat_id,
                              'Choose the one you want to remove',
                              reply_markup=markup)

        elif text == '💰 ADD 💰':
            with open("cryptos.txt", "r") as file:
                all_cr_dict = json.loads(file.read())

            markup = InlineKeyboardMarkup(inline_keyboard=[[
                InlineKeyboardButton(text=f'{str(crypto).upper()}',
                                     callback_data=f'add/{crypto}')
            ] for crypto in all_cr_dict])

            mybot.sendMessage(chat_id,
                              'Choose the one you want to add',
                              reply_markup=markup)

        else:
            send(chat_id, "Sorry, unrecognizable input")

    else:
        send(chat_id,
             "Hi %s, please insert text as input" % msg["from"]["first_name"])
Ejemplo n.º 21
0
 def make_keyboard(self, items):
     keyboard = InlineKeyboardMarkup(inline_keyboard=[[
         InlineKeyboardButton(text=item['title'], url=item['url'])
     ] for item in items])
     return keyboard
Ejemplo n.º 22
0
def on_chat_message(msg):

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

    input_data = msg['text']
    if chat_id in model_choice_store:
        model_choice = model_choice_store[chat_id]
    else:
        model_choice = None

    if input_data == '/start':
        keyboard = InlineKeyboardMarkup(
            inline_keyboard=[[
                InlineKeyboardButton(text=u'Прогноз добычи "сланцевой" нефти',
                                     callback_data='shale')
            ],
                             [
                                 InlineKeyboardButton(
                                     text=u'ВИЭ Европы',
                                     callback_data='renewables')
                             ]])
        TelegramBot.sendMessage(
            chat_id,
            u'Выберите модель. Для изменения выбора нажмите /start или другую кнопку',
            reply_markup=keyboard)

    elif model_choice == 'shale':
        input_data = input_data.split(
        )  # введённый текст переделываем в массив

        if input_data[0][:1] == '/':
            input_data[0] = input_data[0][1:]  # обрезаем слеш

        if is_int(input_data[0]) is True and is_float(input_data[1]) is True:
            input_data = list(map(float,
                                  input_data))  # сценарии буровых в float
            input_data[0] = int(input_data[0])  # месяцы в int
            draw_shale(input_data)  # запуск модели с входными параметрами
            time.sleep(1)
            TelegramBot.sendPhoto(chat_id,
                                  open('chart_shale.png',
                                       'rb'))  # отправка графика в чат
        else:
            TelegramBot.sendMessage(chat_id,
                                    'Shale oil forecast: Wrong arguments')

    elif model_choice == 'renewables':
        input_data = input_data.split(
        )  # введённый текст переделываем в массив

        if input_data[0][:1] == '/':
            input_data[0] = input_data[0][1:]  # обрезаем слеш

        if is_int(input_data[0]) is True and is_float(input_data[1]) is True and is_float(input_data[2]) is True and is_float(input_data[2]) is True \
           and len(input_data) == 4:
            print 'renew entered'
            input_data = list(map(float,
                                  input_data))  # сценарии буровых в float
            month = int(input_data[0] - 1)
            start_date = month * 30.4
            end_date = start_date + 30.4
            wind_multiplier = [input_data[1]]
            solar_multiplier = [input_data[2]]
            capacity_storage = [input_data[3]]
            input_data[0] = int(input_data[0])  # месяцы в int
            draw_renew(1, wind_multiplier, solar_multiplier, capacity_storage,
                       wind_price, solar_price, gas_price, price_kwh_storage,
                       discount_rate_storage, years_storage, start_date,
                       end_date)  # запуск модели с входными параметрами
            time.sleep(1)
            TelegramBot.sendPhoto(chat_id,
                                  open('chart_renew.png',
                                       'rb'))  # отправка графика в чат
        else:
            TelegramBot.sendMessage(chat_id,
                                    'Europe renewables: Wrong arguments')
Ejemplo n.º 23
0
def handle(msg):
    content_type, chat_type, chat_id = telepot.glance(msg)
    print(content_type, chat_type, chat_id)  # debug msg received

    if content_type == 'text':
        response = bot.getUpdates()
        print(response)  # debug id response
        # bot.sendMessage(chat_id, msg['text'])
        msg_received = msg['text'].lower()
        print(msg['text'])  # debug input
        print(msg_received)  # debug lowered input
        if msg_received == '/start':
            print("bot started")
            bot.sendMessage(
                chat_id,
                "Hi! I'm a bot that tells you your course schedule and plan your meetings! Feel free to ask me stuff :)"
            )
            bot.sendMessage(
                chat_id,
                "If you want to know your course schedule, type in Course. If you want to plan your meetings, type in Meetings. If you want to know anything about me, just type in whatever you want and hope I understand :)"
            )
        elif msg_received == 'hi':
            bot.sendMessage(
                chat_id, reply_dict[msg_received] + ', ' +
                response[0]['message']['from']['first_name'] + '!')
        elif msg_received == 'hi bot':
            bot.sendMessage(
                chat_id, reply_dict[msg_received] + ', ' +
                response[0]['message']['from']['first_name'] + '!')
        elif msg_received == 'hello':
            bot.sendMessage(
                chat_id, reply_dict[msg_received] + ', ' +
                response[0]['message']['from']['first_name'] + '!')
        elif msg_received == 'good morning':
            bot.sendMessage(
                chat_id, reply_dict[msg_received] + ', ' +
                response[0]['message']['from']['first_name'] + '!')
        elif msg_received == 'good afternoon':
            bot.sendMessage(
                chat_id, reply_dict[msg_received] + ', ' +
                response[0]['message']['from']['first_name'] + '!')
        elif msg_received == 'good evening':
            bot.sendMessage(
                chat_id, reply_dict[msg_received] + ', ' +
                response[0]['message']['from']['first_name'] + '!')
        elif msg_received == 'good night':
            bot.sendMessage(
                chat_id, reply_dict[msg_received] + ', ' +
                response[0]['message']['from']['first_name'] + '!')
        elif msg_received == 'good day':
            bot.sendMessage(
                chat_id, reply_dict[msg_received] + ', ' +
                response[0]['message']['from']['first_name'] + '!')
        elif msg_received == 'hey':
            bot.sendMessage(
                chat_id, reply_dict[msg_received] + ', ' +
                response[0]['message']['from']['first_name'] + '!')
        elif msg_received.find('rude') != -1:
            bot.sendMessage(chat_id, reply_dict['rude'])
        elif msg_received == 'meetings':
            bot.sendMessage(chat_id, reply_dict[msg_received])
            inlines_keyboard = [[]]
            for i in range(0, len(days)):
                print(days[i])
                inlines_keyboard.append([
                    InlineKeyboardButton(text=days[i], callback_data=days[i])
                ])
            keyboard = InlineKeyboardMarkup(inline_keyboard=inlines_keyboard)
            bot.sendMessage(chat_id, 'Choose a day!', reply_markup=keyboard)
        elif msg_received in reply_dict:
            print(reply_dict[msg_received])  # debug reply
            if second_reply[msg_received] == 1:
                bot.sendMessage(chat_id, reply_dict[msg_received])
        else:
            bot.sendMessage(
                chat_id,
                "Sorry, I don't know what to reply to such conversation yet. :'( "
            )
Ejemplo n.º 24
0
async def addchannel_cmd(msg, db_session, tg_user_id, answer=False):
    print("Add channel command")
    if answer:
        channel = 0
        chat = {}
        if "forward_from_chat" in msg:
            channel = msg['forward_from_chat']['id']
            try:
                chat = await bot.getChat(channel)
            except:
                print("Not id of channel")
        elif "text" in msg:
            match = ""
            if re.match(r"^@\w{3,}$", msg['text']):
                match = msg['text']
            elif re.match(r"^-\d{6,}$", msg['text']):
                match = int(msg['text'])
            if match:
                try:
                    chat = await bot.getChat(match)
                    channel = chat['id']
                except:
                    print("Unknown name")
        else:
            raise ("Unknown type in place of waiting new channel id")

        if chat and chat['type'] == "channel":
            admins = {}
            try:
                admins = await bot.getChatAdministrators(channel)
                pprint(admins)
            except:
                sent = await bot.sendMessage(
                    tg_user_id, "Bot is not an administartor of this channel"
                )  #В БОЛЬШУЮ ПЕРЕМЕННУЮ
            for admin in admins:
                if admin['user']['id'] == 548347944:  #НОМЕР БОТА. УБРАТЬ!!!
                    if admin['can_delete_messages'] and admin[
                            'can_edit_messages'] and admin[
                                'can_invite_users'] and admin[
                                    'can_post_messages']:
                        db_tg_user = utils.get_tg_user(db_session, tg_user_id)
                        channels = utils.get_channels(db_session, db_tg_user)
                        if not channel in channels:
                            print(channels)
                            utils.add_tg_channel(db_session, channel,
                                                 db_tg_user)
                            sent = await bot.sendMessage(
                                tg_user_id,
                                "This channel has successfully been added"
                            )  #В БОЛЬШУЮ ПЕРЕМЕННУЮ
                        else:
                            sent = await bot.sendMessage(
                                tg_user_id, "This channel was already added"
                            )  #В БОЛЬШУЮ ПЕРЕМЕННУЮ
                        return
                    else:
                        sent = await bot.sendMessage(
                            tg_user_id, "Bot have not required permissions"
                        )  #В БОЛЬШУЮ ПЕРЕМЕННУЮ
                    break

    keyboard = InlineKeyboardMarkup(inline_keyboard=[
        [
            InlineKeyboardButton(text=CANCEL_BTN[0],
                                 callback_data='cancel_command')
        ],
    ])

    sent = await bot.sendMessage(tg_user_id,
                                 ADD_CHANNEL_MSG[1],
                                 reply_markup=keyboard)
    DIALOG_STATE = "hard_addchannel"  #ДОЛЖНО БЫТЬ В БАЗЕ
Ejemplo n.º 25
0
    def on_callback_query(self, msg):
        query_id, from_id, query_data = telepot.glance(msg,
                                                       flavor='callback_query')

        #Handle Callback Query
        inline_message_id = msg['message']['chat']['id'], msg['message'][
            'message_id']
        bot.editMessageReplyMarkup(inline_message_id, reply_markup=None)

        #for finding stalls by location, provide list of canteens for user to choose from
        if (query_data == 'can'):
            #choice1="Canteen"
            canteen_keyboard = InlineKeyboardMarkup(inline_keyboard=[
                [InlineKeyboardButton(text='Canteen 1', callback_data='can1')],
                [InlineKeyboardButton(text='Canteen 2', callback_data='can2')],
                [InlineKeyboardButton(text='Canteen 4', callback_data='can2')],
                [InlineKeyboardButton(text='Canteen 9', callback_data='can9')],
                [
                    InlineKeyboardButton(text='Canteen 11',
                                         callback_data='can11')
                ],
                [
                    InlineKeyboardButton(text='Canteen 13',
                                         callback_data='can13')
                ],
                [
                    InlineKeyboardButton(text='Canteen 14',
                                         callback_data='can14')
                ],
                [
                    InlineKeyboardButton(text='Canteen 16',
                                         callback_data='can16')
                ],
                [InlineKeyboardButton(text='Koufu', callback_data='koufu')],
                [
                    InlineKeyboardButton(text='NIE Canteen',
                                         callback_data='niecan')
                ],
                [
                    InlineKeyboardButton(text='North Hill Canteen',
                                         callback_data='nhcan')
                ],
                [
                    InlineKeyboardButton(text='North Spine Food Court',
                                         callback_data='nspine')
                ],
                [
                    InlineKeyboardButton(text='Pioneer Canteen',
                                         callback_data='piocan')
                ],
            ])

            bot.sendMessage(from_id,
                            "Select Canteen",
                            reply_markup=canteen_keyboard)
        #thereafter, use findstall.py to output list of filtered and sorted stalls in selected canteen
        elif (query_data == 'can1'):
            response = findstall("Canteen", "Canteen 1")
            bot.sendMessage(from_id, response)
        elif (query_data == 'can2'):
            response = findstall("Canteen", "Canteen 2")
            bot.sendMessage(from_id, response)
        elif (query_data == 'can4'):
            response = findstall("Canteen", "Canteen 4")
            bot.sendMessage(from_id, response)
        elif (query_data == 'can9'):
            response = findstall("Canteen", "Canteen 9")
            bot.sendMessage(from_id, response)
        elif (query_data == 'can11'):
            response = findstall("Canteen", "Canteen 11")
            bot.sendMessage(from_id, response)
        elif (query_data == 'can13'):
            response = findstall("Canteen", "Canteen 13")
            bot.sendMessage(from_id, response)
        elif (query_data == 'can14'):
            response = findstall("Canteen", "Canteen 14")
            bot.sendMessage(from_id, response)
        elif (query_data == 'can16'):
            response = findstall("Canteen", "Canteen 16")
            bot.sendMessage(from_id, response)
        elif (query_data == 'koufu'):
            response = findstall("Canteen", "Koufu")
            bot.sendMessage(from_id, response)
        elif (query_data == 'niecan'):
            response = findstall("Canteen", "NIE Canteen")
            bot.sendMessage(from_id, response)
        elif (query_data == 'nhcan'):
            response = findstall("Canteen", "North Hill Canteen")
            bot.sendMessage(from_id, response)
        elif (query_data == 'nspine'):
            response = findstall("Canteen", "North Spine Foodcourt")
            bot.sendMessage(from_id, response)
        elif (query_data == 'piocan'):
            response = findstall("Canteen", "Pioneer Canteen")
            bot.sendMessage(from_id, response)

        #for finding stalls by cuisine, provide list of cuisine types for user to choose from
        elif (query_data == 'cui'):
            cuisine_keyboard = InlineKeyboardMarkup(inline_keyboard=[
                [InlineKeyboardButton(text="Drinks", callback_data="cui1")],
                [InlineKeyboardButton(text="Western", callback_data="cui2")],
                [InlineKeyboardButton(text="Chinese", callback_data="cui3")],
                [InlineKeyboardButton(text="Muslim", callback_data="cui4")],
                [InlineKeyboardButton(text="Indian", callback_data="cui5")],
                [InlineKeyboardButton(text="Japanese", callback_data="cui6")],
                [InlineKeyboardButton(text="Korean", callback_data="cui7")],
                [
                    InlineKeyboardButton(text="Yong Tau Fu",
                                         callback_data="cui8")
                ],
                [
                    InlineKeyboardButton(text="Economical Rice",
                                         callback_data="cui9")
                ],
                [
                    InlineKeyboardButton(text="Chicken Rice",
                                         callback_data="cui10")
                ],
                [InlineKeyboardButton(text="Asian", callback_data="cui11")],
                [InlineKeyboardButton(text="Dessert", callback_data="cui12")],
                [InlineKeyboardButton(text="Malay", callback_data="cui13")],
                [InlineKeyboardButton(text="Thai", callback_data="cui14")],
                [
                    InlineKeyboardButton(text="Vietnamese",
                                         callback_data="cui15")
                ],
            ])
            bot.sendMessage(from_id,
                            "Select Cuisine",
                            reply_markup=cuisine_keyboard)

        #thereafter, use findstall.py to output list of filtered and sorted stalls for selected cuisine
        elif (query_data == 'cui1'):
            response = findstall("Cuisine", "Drinks")
            bot.sendMessage(from_id, response)
        elif (query_data == 'cui2'):
            response = findstall("Cuisine", "Western")
            bot.sendMessage(from_id, response)
        elif (query_data == 'cui3'):
            response = findstall("Cuisine", "Chinese")
            bot.sendMessage(from_id, response)
        elif (query_data == 'cui4'):
            response = findstall("Cuisine", "Muslim")
            bot.sendMessage(from_id, response)
        elif (query_data == 'cui5'):
            response = findstall("Cuisine", "Indian")
            bot.sendMessage(from_id, response)
        elif (query_data == 'cui6'):
            response = findstall("Cuisine", "Japanese")
            bot.sendMessage(from_id, response)
        elif (query_data == 'cui7'):
            response = findstall("Cuisine", "Korean")
            bot.sendMessage(from_id, response)
        elif (query_data == 'cui8'):
            response = findstall("Cuisine", "Yong Tau Fu")
            bot.sendMessage(from_id, response)
        elif (query_data == 'cui9'):
            response = findstall("Cuisine", "Economical Rice")
            bot.sendMessage(from_id, response)
        elif (query_data == 'cui10'):
            response = findstall("Cuisine", "Chicken Rice")
            bot.sendMessage(from_id, response)
        elif (query_data == 'cui11'):
            response = findstall("Cuisine", "Asian")
            bot.sendMessage(from_id, response)
        elif (query_data == 'cui12'):
            response = findstall("Cuisine", "Dessert")
            bot.sendMessage(from_id, response)
        elif (query_data == 'cui13'):
            response = findstall("Cuisine", "Malay")
            bot.sendMessage(from_id, response)
        elif (query_data == 'cui14'):
            response = findstall("Cuisine", "Thai")
            bot.sendMessage(from_id, response)
        elif (query_data == 'cui15'):
            response = findstall("Cuisine", "Vietnamese")
            bot.sendMessage(from_id, response)

        # answer callback query or else telegram will forever wait on this
        bot.answerCallbackQuery(query_id)
Ejemplo n.º 26
0
async def channel_handler(msg):
    print("channel handler")
    if not "text" in msg: return  #ПЕРЕСМОТРЕТЬ + сделать для фото

    channelusername = "******" + msg['chat']['username']
    channel_id = msg['chat']['id']
    ents = []  #entities of post
    text = ""  #text of post
    msg_id = msg['message_id']

    if "text" in msg:
        text = msg['text']
    if "entities" in msg:
        ents = msg['entities']

    urls = []
    bold = []
    italic = []
    code = []
    pre = []
    text_link = []
    pics = []
    if text and ents:
        for ent in ents:
            if ent['type'] == "text_link":
                urls.append(ent['url'])
                start_ch = ent['offset']
                end_ch = ent['offset'] + ent['length']
                text_link.append((start_ch, end_ch, ent['url']))
            elif ent['type'] == "bold":
                start_ch = ent['offset']
                end_ch = ent['offset'] + ent['length']
                bold.append((start_ch, end_ch))
            elif ent['type'] == "italic":
                start_ch = ent['offset']
                end_ch = ent['offset'] + ent['length']
                italic.append((start_ch, end_ch))
            elif ent['type'] == "code":
                start_ch = ent['offset']
                end_ch = ent['offset'] + ent['length']
                code.append((start_ch, end_ch))
            elif ent['type'] == "pre":
                start_ch = ent['offset']
                end_ch = ent['offset'] + ent['length']
                pre.append((start_ch, end_ch))
            elif ent['type'] == "url":
                start_ch = ent['offset']
                end_ch = ent['offset'] + ent['length']
                urls.append(text[start_ch:end_ch])

    for url_item in urls:
        if url_item.endswith('.jpg') or url_item.endswith(
                '.jpeg') or url_item.endswith('.png') or url_item.endswith(
                    '.gif'):  #оптимизировать списком граф.расширения
            picname_pos = url_item.rfind("/") + 1
            pic_item = "pics/" + url_item[picname_pos:]
            pics.append(pic_item)
            filereq = requests.get(url_item, stream=True)
            with open(pic_item, "wb") as receive:
                receive.write(filereq.content)
            del filereq

    post_id = vk_poster(VK_TOKEN,
                        VK_APP_ID,
                        VK_GRP_ID,
                        text=text,
                        bold=bold,
                        pics=pics,
                        urls=["https://t.me/{}".format(tg_channel)])

    keyboard = InlineKeyboardMarkup(
        inline_keyboard=[  #Добавить счётчик переходов
            [
                InlineKeyboardButton(text='VK',
                                     url='https://vk.com/wall{}_{}'.format(
                                         VK_GRP_ID, post_id)),
                InlineKeyboardButton(text='FB', url='https://fb.com/'),
                InlineKeyboardButton(text='Tw', url='https://twitter.com/')
            ],
        ])
    try:
        sent = await bot.editMessageReplyMarkup((channel_id, msg_id),
                                                reply_markup=keyboard)
    except Exception as e:
        print("Exception of editing message", e)
        markdown_text = message_formater(text, bold, italic, code, pre,
                                         text_link)
        if markdown_text:
            sent = await bot.deleteMessage((channel_id, msg_id))
            sent = await bot.sendMessage(channel_id,
                                         markdown_text,
                                         parse_mode='Markdown',
                                         disable_notification=True,
                                         reply_markup=keyboard)
Ejemplo n.º 27
0
def getRigServerData(chat_id, markupReturnData, closeList):
    markup_contents = []
    markup_contents_2ndHalf = []
    minerUpStatus = ["empty"]
    count = 1
    message_server = ""

    while 1:
        try:
            #send stats of rig to cilent
            aFile = open(userNameDict[chat_id] + "_" + str(count) + "_" +
                         "statsServer.txt")

            #read stats of the selected miner
            allDetails = aFile.readlines()

            #if file time difference is less than 5mins(300sec), means it's still up (using epoch as time)
            if abs(int(time.time()) - int(allDetails[0])) < 300:
                #blue circle picture
                minerUpStatus.append("🔵")
            else:
                #red circle picture
                minerUpStatus.append("🔴")

            # only read stats of the miner selected by the user
            if str(count) != markupReturnData[1] or closeList:
                aFile.close()
                count += 1
                continue

        #if file does not exist
        except IOError:
            #exception thrown if file doesn't exist
            break

        #if cannot find username in dict (RAM's database)
        except KeyError:
            bot.sendMessage(
                chat_id,
                "Error searching for username. \nPlease input \n/start <username> \nagain."
            )
            return

        except Exception as ex:
            print(ex, "exception when reading file")

        else:
            #clear it each markup must have text so example mine2 markup will send miner1's stats as text
            message_server = ""

            #No. GPUs
            allDetails[46] = allDetails[46].split()
            message_server += "\nNo. of GPUs = " + allDetails[46][1]

            #Temp
            allDetails[31] = allDetails[31].split()
            message_server += "\nTemp = " + allDetails[31][1] + "degrees\n"

            #Status
            allDetails[43] = allDetails[43].split()
            message_server += "\nMining Status = " + allDetails[43][
                3] + " " + allDetails[43][4]

            #Hash rate
            allDetails[49] = allDetails[49].split()
            message_server += "\nHash rate = " + allDetails[49][1]

            #pop out from RAM to save RAM space since no longer inused
            aFile.close()

        count += 1

    #create buttons of miner1 to the miner number that user selected to see the stats
    #condition assignment is used so that it won't stop at int(markupReturnData[1]) if closeList is True
    for i in range(1, count if closeList else int(markupReturnData[1]) + 1):
        markup_contents.append([
            InlineKeyboardButton(
                text="miner" + str(i) + " " + str(minerUpStatus[i]),
                callback_data=markupReturnData[0] + "_" + str(i))
        ])

        if i == int(markupReturnData[1]):
            if not closeList:
                if len(markup_contents) != 0:
                    markup_contents.pop()
                markup_contents.append([
                    InlineKeyboardButton(
                        text="miner" + str(i) + " " + str(minerUpStatus[i]),
                        callback_data=markupReturnData[0] + "+" + str(i))
                ])

    for i in range(int(markupReturnData[1]) + 1, count):

        markup_contents_2ndHalf.append([
            InlineKeyboardButton(
                text="miner" + str(i) + " " + str(minerUpStatus[i]),
                callback_data=markupReturnData[0] + "_" + str(i))
        ])

    #create Markup from
    minerInfoButtons = InlineKeyboardMarkup(inline_keyboard=markup_contents)

    #useful when server restarted and user clicked on previous inLine buttons
    try:
        print(markupReturnData)
        markupDict[chat_id] = bot.editMessageText(
            telepot.message_identifier(markupDict[chat_id]),
            text=markupReturnData[0] + " status",
            reply_markup=minerInfoButtons)
    except Exception as ex:
        print(ex, "editMessage failed")
        markupDict[chat_id] = bot.sendMessage(chat_id,
                                              text=markupReturnData[0] +
                                              " status",
                                              reply_markup=minerInfoButtons)

    minerInfoButtons = InlineKeyboardMarkup(
        inline_keyboard=markup_contents_2ndHalf)

    #Don't send it there are no 2nd half of the buttons after the drop down list
    if len(message_server) != 0:
        #useful when server restarted and user clicked on previous inLine buttons
        #markupDict[str(chat_id)+str("_1")] instead of markupDict[chat_id] as is to store identifier of 2nd half of the message/buttons
        try:
            markupDict[str(chat_id) + str("_1")] = bot.editMessageText(
                telepot.message_identifier(markupDict[str(chat_id) +
                                                      str("_1")]),
                text=message_server,
                reply_markup=minerInfoButtons)
        except:
            markupDict[str(chat_id) + str("_1")] = bot.sendMessage(
                chat_id, text=message_server, reply_markup=minerInfoButtons)
    else:
        #try to delete dropdownlist if user selected to close it
        try:
            bot.deleteMessage(
                telepot.message_identifier(markupDict[str(chat_id) +
                                                      str("_1")]))
        except:
            pass
Ejemplo n.º 28
0
    def reply_text(self, text):
        reply = "meow"
        markup = ReplyKeyboardRemove()
        if text.startswith("/appmedia"):
            reply = "Which ranking?"
            markup = InlineKeyboardMarkup(inline_keyboard=[
                [InlineKeyboardButton(text='Appmedia SSR Ranking', callback_data='appmedia_ssr')],
                [InlineKeyboardButton(text='Appmedia SR Ranking', callback_data='appmedia_sr')]
            ])
        if text.startswith("/servant"):
            keyboards = []
            for i in self._servants.keys():
                keyboards.append([KeyboardButton(text="★{} {}".format(j, i)) for j in self._servants[i].keys()])
            markup = ReplyKeyboardMarkup(keyboard=keyboards, one_time_keyboard=True)

            # "Saber", "Archer", "Lancer", "Rider", "Caster", "Assassin", "Berserker", "Shielder", "Ruler", "Avenger", "MoonCancer", "AlterEgo", "Foreigner"
            reply = "Please choose class and rare"

        if text.startswith("★"):
            fgorare, fgoclass = text.split()
            fgorare = int(fgorare[1])
            reply = self._servants[fgoclass][fgorare]
        if text.startswith("/hougu"):
            reply = """
早见表
https://docs.google.com/spreadsheets/d/1ru35rHQ9DMsQcBXHPgUD5XDO-mSvR_j1fFTB_V507zw/htmlview

fc2 宝具計算
fgotouka.web.fc2.com
国人宝具計算
https://xianlechuanshuo.github.io/fgo2/calc4.html
            """
        if text.startswith("/drop"):
            reply = "FGO効率劇場\nhttps://docs.google.com/spreadsheets/d/1TrfSDteVZnjUPz68rKzuZWZdZZBLqw03FlvEToOvqH0/htmlview?sle=true#"
        if text.startswith("/wiki"):
            servant_name = " ".join(text.split()[1:])
            if servant_name:
                query_page_url = "https://www9.atwiki.jp/f_go/?cmd=wikisearch&keyword={}".format(servant_name)
                r = requests.get(query_page_url)
                if r.status_code == 200:
                    rq = q(r.content.decode("utf-8"))
                    links = rq("#wikibody li a")
                    filtered_links = [q(x) for x in links if not any(("コメント" in q(x).text(), "ボイス" in q(x).text(), "性能" in q(x).text()))][:10]
                    reply = ""
                    for i in filtered_links:
                        reply += "{}\nhttps:{}\n\n".format(i.html(), i.attr("href"))
                else:
                    reply = "connection timeout {}".format(r.status_code)
            else:
                reply = "https://www9.atwiki.jp/f_go/pages/671.html"

        if text.startswith("/price"):
            reply = "google: 9800 JPY = "
            google_finance_url = "https://finance.google.com/finance/converter?a={}&from={}&to={}".format(9800, "JPY", "CNY")
            result = requests.get(google_finance_url)
            if result.status_code == 200:
                rcontent = q(result.content)
                rcontent = rcontent("#currency_converter_result .bld").text()
                reply += rcontent
            jeanne_h5_url = "http://h5.m.taobao.com/awp/core/detail.htm?id=553971150031"
            reply += "\nJeanne {}".format(jeanne_h5_url)

            tu_jihua_url = "https://item.taobao.com/item.htm?spm=2013.1.w4023-16844942798.13.5692e503t594AU&id=558505049792"
            reply += "\n秃计划 {}".format(tu_jihua_url)

        if text.startswith("/gamewith"):
            reply = "https://gamewith.jp/fgo/article/show/62409"

        if text.startswith("/summon"):
            simulator_url = "https://konatasick.github.io/test_simulator/pool.html?"
            simulator_js = "https://konatasick.github.io/test_simulator/js/index.js"
            reply = "Summon list\n%s\n\n" % simulator_url
            r = requests.get(simulator_js)
            if r.status_code == 200:
                rcontent = r.content.decode("utf-8")
                rcontent = rcontent.replace("\n", "")
                summon_json = re.findall('"sites"\:(.*)\/\*', rcontent)[0].rstrip('}')
                summon_json = json.loads(summon_json)
                summon_json_last_ten = summon_json[::-1][:10]
                for i in summon_json_last_ten:
                    reply += "{} {}{}\n".format(i["name"], simulator_url, i["info"])

        if text.startswith("/help") or text.startswith("/start"):
            reply = """
Author: @fdb713
/appmedia - appmedia ranking
/drop - drop statistics
/gamewith - gamewith ranking link
/hougu - hougu damage quick reference
/price - compare JPY to CNY and 3rd-party charge
/servant - send link of servants by rare and class from atwiki
/summon - simulate summon
/wiki - search and send link of servant or other keywords on atwiki page
/help or /start - show this message
            """

        return reply, markup
Ejemplo n.º 29
0
def callback(message, matches, chat_id):
    locks = {
        'lock_link': 'قفل لینک📎',
        'lock_username': '******',
        'lock_photo': 'قفل عکس🖼',
        'lock_doc': 'قفل گیف🌠',
        'lock_film': 'قفل فیلم🎥',
        'lock_music': 'قفل موزیک🎼',
        'lock_voice': 'قفل ویس🗣',
        'lock_game': 'قفل بازی🏓',
        'lock_doc': 'قفل فایل📁',
        'lock_contact': 'قفل مخاطب🔢',
        'lock_sticker': 'قفل استیکر🎭',
        'lock_bots': 'قفل ورود ربات🤖',
        'lock_fwd': 'قفل فوروارد 🔂',
        'lock_spam': 'قفل اسپم 👿',
        'lock_tg': 'قفل پیام ورود و خروج 🚶',
        'lock_loc': 'قفل لوکیشن(مکان)🗺',
        'lock_all': 'قفل گروه🔕',
        'lock_video_note': 'قفل ویدیو مسیج🤳'
    }
    query_id, from_id, data = telepot.glance(message, flavor='callback_query')
    if is_mod2(message['message'], message):
        if data == "/admins":
            owner = r.hget('owner', chat_id)
            if owner:
                oner = '[{}](tg://user?id={})'.format(owner, owner)
            else:
                oner = 'وجود ندارد❌'
            mods = r.smembers('mod:{}'.format(chat_id))
            if mods:
                mod = ''
                for x in mods:
                    mod += '\n>[{}](tg://user?id={})'.format(x, x)
            else:
                mod = 'وجود ندارد❌'

            text = '''👤 ادمین اصلی : {}

            👥 سایر ادمین ها :
            {}'''.format(oner, mod)

            key = [[
                InlineKeyboardButton(text='🏛 منوی اصلی',
                                     callback_data='/back'),
            ]]
            markup = InlineKeyboardMarkup(inline_keyboard=key)
            msgid = (chat_id, message['message']['message_id'])
            return Message(chat_id).edit_message(msgid,
                                                 text,
                                                 parse_mode="Markdown",
                                                 reply_markup=markup)
        if data == '/back':
            text = "📋به پنل تنظیمات ربات خوش آمدید برای مدیریت گروه از کیبورد زیر استفاده کنید." \
                   "(فقط ادمین های ربات در گروه قابلیت کار کردن با این کیبورد را دارند)"
            ex = int(r.ttl('expire:{}'.format(chat_id))) - time.time()
            days = int(ex / 86400)
            key = [[
                InlineKeyboardButton(text='🔐 منوی قفل ها',
                                     callback_data='/locks'),
                InlineKeyboardButton(text='📝تنظیمات پیام',
                                     callback_data='/pmsetting'),
            ],
                   [
                       InlineKeyboardButton(text='👥لیست مدیران',
                                            callback_data='/admins'),
                   ],
                   [
                       InlineKeyboardButton(text='روز {}'.format(days),
                                            callback_data='/expire'),
                       InlineKeyboardButton(text='📆شارژ گروه',
                                            callback_data='/expire'),
                   ],
                   [
                       InlineKeyboardButton(text='💡ورود به کانال راهنما💡',
                                            url='https://t.me/spntaHelp'),
                   ]]
            markup = InlineKeyboardMarkup(inline_keyboard=key)
            msgid = (chat_id, message['message']['message_id'])
            return Message(chat_id).edit_message(msgid,
                                                 text,
                                                 parse_mode="Markdown",
                                                 reply_markup=markup)
        if data == '/pmsetting':
            get_spam = r.hget('get_spam', chat_id) or '10,1'
            value = get_spam.split(',')
            NUM_MAX = value[0]
            TIME_LIMIT = value[1]
            key = [[
                InlineKeyboardButton(text='🔽 تعداد مجاز پیام در دقیقه 🔽',
                                     callback_data='hem')
            ],
                   [
                       InlineKeyboardButton(text='➖',
                                            callback_data='spam_num_down'),
                       InlineKeyboardButton(text='{}'.format(NUM_MAX),
                                            callback_data='hem'),
                       InlineKeyboardButton(text='➕',
                                            callback_data='spam_num_up'),
                   ],
                   [
                       InlineKeyboardButton(text='               ',
                                            callback_data='hem')
                   ],
                   [
                       InlineKeyboardButton(
                           text='🔽 تایم محدودیت کاربر(به دقیقه)🔽',
                           callback_data='hem')
                   ],
                   [
                       InlineKeyboardButton(text='➖',
                                            callback_data='spam_time_down'),
                       InlineKeyboardButton(text='{}'.format(TIME_LIMIT),
                                            callback_data='hem'),
                       InlineKeyboardButton(text='➕',
                                            callback_data='spam_time_up'),
                   ],
                   [
                       InlineKeyboardButton(text='🏛 منوی اصلی',
                                            callback_data='/back'),
                   ]]
            text = 'منوی تنظیمات ارسال پیام🗯'
            markup = InlineKeyboardMarkup(inline_keyboard=key)
            msgid = (chat_id, message['message']['message_id'])
            return Message(chat_id).edit_message(msgid,
                                                 text,
                                                 parse_mode="Markdown",
                                                 reply_markup=markup)
        spam = re.compile('spam_')
        if spam.search(data):
            pat = data.replace('spam_', '')
            if pat == 'time_down':
                getwww = r.hget('get_spam', chat_id) or '10,1'
                vvv = getwww.split(',')
                mmm = vvv[1]
                sss = vvv[0]
                num = int(mmm) - 1
                r.hset('get_spam', chat_id, '{},{}'.format(sss, num))
                get_spam = r.hget('get_spam', chat_id) or '10,1'
                value = get_spam.split(',')
                NUM_MAX = value[0]
                TIME_LIMIT = value[1]
                key = [[
                    InlineKeyboardButton(text='🔽 تعداد مجاز پیام در دقیقه 🔽',
                                         callback_data='hem')
                ],
                       [
                           InlineKeyboardButton(text='➖',
                                                callback_data='spam_num_down'),
                           InlineKeyboardButton(text='{}'.format(NUM_MAX),
                                                callback_data='hem'),
                           InlineKeyboardButton(text='➕',
                                                callback_data='spam_num_up'),
                       ],
                       [
                           InlineKeyboardButton(text='               ',
                                                callback_data='hem')
                       ],
                       [
                           InlineKeyboardButton(
                               text='🔽 تایم محدودیت کاربر(به دقیقه)🔽',
                               callback_data='hem')
                       ],
                       [
                           InlineKeyboardButton(
                               text='➖', callback_data='spam_time_down'),
                           InlineKeyboardButton(text='{}'.format(num),
                                                callback_data='hem'),
                           InlineKeyboardButton(text='➕',
                                                callback_data='spam_time_up'),
                       ],
                       [
                           InlineKeyboardButton(text='🏛 منوی اصلی',
                                                callback_data='/back'),
                       ]]
                text = '''منوی تنظیمات ارسال پیام🗯
(فقط ادمین های ربات در گروه قابلیت کار کردن با این کیبورد را دارند)

اخرین تغییرات :
👤 [{}](tg://user?id={})
├ `Pm setting`
└ `{} => {}`'''.format(message['from']['first_name'], message['from']['id'],
                       pat, num)
                markup = InlineKeyboardMarkup(inline_keyboard=key)
                msgid = (chat_id, message['message']['message_id'])
                return Message(chat_id).edit_message(msgid,
                                                     text,
                                                     parse_mode="Markdown",
                                                     reply_markup=markup)
            if pat == 'time_up':
                getwww = r.hget('get_spam', chat_id) or '10,1'
                vvv = getwww.split(',')
                mmm = vvv[1]
                sss = vvv[0]
                num = int(mmm) + 1
                r.hset('get_spam', chat_id, '{},{}'.format(sss, num))
                get_spam = r.hget('get_spam', chat_id) or '10,1'
                value = get_spam.split(',')
                NUM_MAX = value[0]
                TIME_LIMIT = value[1]
                key = [[
                    InlineKeyboardButton(text='🔽 تعداد مجاز پیام در دقیقه 🔽',
                                         callback_data='hem')
                ],
                       [
                           InlineKeyboardButton(text='➖',
                                                callback_data='spam_num_down'),
                           InlineKeyboardButton(text='{}'.format(NUM_MAX),
                                                callback_data='hem'),
                           InlineKeyboardButton(text='➕',
                                                callback_data='spam_num_up'),
                       ],
                       [
                           InlineKeyboardButton(text='               ',
                                                callback_data='hem')
                       ],
                       [
                           InlineKeyboardButton(
                               text='🔽 تایم محدودیت کاربر(به دقیقه)🔽',
                               callback_data='hem')
                       ],
                       [
                           InlineKeyboardButton(
                               text='➖', callback_data='spam_time_down'),
                           InlineKeyboardButton(text='{}'.format(num),
                                                callback_data='hem'),
                           InlineKeyboardButton(text='➕',
                                                callback_data='spam_time_up'),
                       ],
                       [
                           InlineKeyboardButton(text='🏛 منوی اصلی',
                                                callback_data='/back'),
                       ]]
                text = '''منوی تنظیمات ارسال پیام🗯
(فقط ادمین های ربات در گروه قابلیت کار کردن با این کیبورد را دارند)

اخرین تغییرات :
👤 [{}](tg://user?id={})
├ `Pm setting`
└ `{} => {}`'''.format(message['from']['first_name'], message['from']['id'],
                       pat, num)
                markup = InlineKeyboardMarkup(inline_keyboard=key)
                msgid = (chat_id, message['message']['message_id'])
                return Message(chat_id).edit_message(msgid,
                                                     text,
                                                     parse_mode="Markdown",
                                                     reply_markup=markup)
            if pat == 'num_down':
                getwww = r.hget('get_spam', chat_id) or '10,1'
                vvv = getwww.split(',')
                mmm = vvv[0]
                sss = vvv[1]
                num = int(mmm) - 1
                r.hset('get_spam', chat_id, '{},{}'.format(num, sss))
                get_spam = r.hget('get_spam', chat_id) or '10,1'
                value = get_spam.split(',')
                NUM_MAX = value[0]
                TIME_LIMIT = value[1]
                key = [[
                    InlineKeyboardButton(text='🔽 تعداد مجاز پیام در دقیقه 🔽',
                                         callback_data='hem')
                ],
                       [
                           InlineKeyboardButton(text='➖',
                                                callback_data='spam_num_down'),
                           InlineKeyboardButton(text='{}'.format(num),
                                                callback_data='hem'),
                           InlineKeyboardButton(text='➕',
                                                callback_data='spam_num_up'),
                       ],
                       [
                           InlineKeyboardButton(text='               ',
                                                callback_data='hem')
                       ],
                       [
                           InlineKeyboardButton(
                               text='🔽 تایم محدودیت کاربر(به دقیقه)🔽',
                               callback_data='hem')
                       ],
                       [
                           InlineKeyboardButton(
                               text='➖', callback_data='spam_time_down'),
                           InlineKeyboardButton(text='{}'.format(TIME_LIMIT),
                                                callback_data='hem'),
                           InlineKeyboardButton(text='➕',
                                                callback_data='spam_time_up'),
                       ],
                       [
                           InlineKeyboardButton(text='🏛 منوی اصلی',
                                                callback_data='/back'),
                       ]]
                text = '''منوی تنظیمات ارسال پیام🗯
(فقط ادمین های ربات در گروه قابلیت کار کردن با این کیبورد را دارند)

اخرین تغییرات :
👤 [{}](tg://user?id={})
├ `Pm setting`
└ `{} => {}`'''.format(message['from']['first_name'], message['from']['id'],
                       pat, num)
                markup = InlineKeyboardMarkup(inline_keyboard=key)
                msgid = (chat_id, message['message']['message_id'])
                return Message(chat_id).edit_message(msgid,
                                                     text,
                                                     parse_mode="Markdown",
                                                     reply_markup=markup)
            if pat == 'num_up':
                getwww = r.hget('get_spam', chat_id) or '10,1'
                vvv = getwww.split(',')
                mmm = vvv[0]
                sss = vvv[1]
                num = int(mmm) + 1
                r.hset('get_spam', chat_id, '{},{}'.format(num, sss))
                get_spam = r.hget('get_spam', chat_id) or '10,1'
                value = get_spam.split(',')
                NUM_MAX = value[0]
                TIME_LIMIT = value[1]
                key = [[
                    InlineKeyboardButton(text='🔽 تعداد مجاز پیام در دقیقه 🔽',
                                         callback_data='hem')
                ],
                       [
                           InlineKeyboardButton(text='➖',
                                                callback_data='spam_num_down'),
                           InlineKeyboardButton(text='{}'.format(num),
                                                callback_data='hem'),
                           InlineKeyboardButton(text='➕',
                                                callback_data='spam_num_up'),
                       ],
                       [
                           InlineKeyboardButton(text='               ',
                                                callback_data='hem')
                       ],
                       [
                           InlineKeyboardButton(
                               text='🔽 تایم محدودیت کاربر(به دقیقه)🔽',
                               callback_data='hem')
                       ],
                       [
                           InlineKeyboardButton(
                               text='➖', callback_data='spam_time_down'),
                           InlineKeyboardButton(text='{}'.format(TIME_LIMIT),
                                                callback_data='hem'),
                           InlineKeyboardButton(text='➕',
                                                callback_data='spam_time_up'),
                       ],
                       [
                           InlineKeyboardButton(text='🏛 منوی اصلی',
                                                callback_data='/back'),
                       ]]
                text = '''منوی تنظیمات ارسال پیام🗯
(فقط ادمین های ربات در گروه قابلیت کار کردن با این کیبورد را دارند)

اخرین تغییرات :
👤 [{}](tg://user?id={})
├ `Pm setting`
└ `{} => {}`'''.format(message['from']['first_name'], message['from']['id'],
                       pat, num)
                markup = InlineKeyboardMarkup(inline_keyboard=key)
                msgid = (chat_id, message['message']['message_id'])
                return Message(chat_id).edit_message(msgid,
                                                     text,
                                                     parse_mode="Markdown",
                                                     reply_markup=markup)

        if data == '/locks':
            key = []
            for lock in locks:
                key.append([
                    InlineKeyboardButton(text=r.hget(lock, chat_id) and '«✔️»'
                                         or '«✖️»',
                                         callback_data='/' + lock),
                    InlineKeyboardButton(text=locks[lock],
                                         callback_data='/' + lock)
                ])
            key.append([
                InlineKeyboardButton(text='🏛 منوی اصلی',
                                     callback_data='/back'),
            ])
            markey = InlineKeyboardMarkup(inline_keyboard=key)

            text = 'برای تغییر حالت قفل بر روی آن کلیک کنید👌'
            msgid = (chat_id, message['message']['message_id'])
            return Message(chat_id).edit_message(msgid,
                                                 text,
                                                 parse_mode="Markdown",
                                                 reply_markup=markey)

        if matches[0] == 'lock_':
            l = matches[0] + matches[1]
            text = '''📋به پنل تنظیمات ربات خوش آمدید برای مدیریت گروه از کیبورد زیر استفاده کنید.
(فقط ادمین های ربات در گروه قابلیت کار کردن با این کیبورد را دارند)

اخرین تغییرات :
👤 [{}](tg://user?id={})
 ├ `settings changed`
 └ `{} =>'''.format(message['from']['first_name'], message['from']['id'], l)
            key = []
            for lock in locks:
                if lock == l:
                    if r.hget(lock, chat_id):
                        r.hdel(lock, chat_id)
                        text += ' OFF`'
                        status = '«✖️»'
                        bot.answerCallbackQuery(query_id, 'غیر فعال شد✖️')
                    else:
                        r.hset(lock, chat_id, True)
                        text += ' ON`'
                        status = '«✔️»'
                        bot.answerCallbackQuery(query_id, 'فعال شد ✔️')
                else:
                    status = r.hget(lock, chat_id) and '«✔️»' or '«✖️»'
                key.append([
                    InlineKeyboardButton(text=status,
                                         callback_data='/' + lock),
                    InlineKeyboardButton(text=locks[lock],
                                         callback_data='/' + lock)
                ])
            key.append([
                InlineKeyboardButton(text='🏛 منوی اصلی',
                                     callback_data='/back'),
            ])
            markey = InlineKeyboardMarkup(inline_keyboard=key)
            msgid = (chat_id, message['message']['message_id'])
            return Message(chat_id).edit_message(msgid,
                                                 text,
                                                 parse_mode="Markdown",
                                                 reply_markup=markey)
Ejemplo n.º 30
0
    def _get_config(self) -> Dict[str, Any]:
        """
        Gets the kwargs for the sending methods.
        :return: kwargs for the sending of the answer
        """

        if self.choices is not None:

            # In the case of 1-dimensional array
            # align the options in pairs of 2
            if isinstance(self.choices[0], (str, tuple)):
                self.choices = [[
                    y for y in self.choices[x * 2:(x + 1) * 2]
                ] for x in range(int(math.ceil(len(self.choices) / 2)))]

            # Prepare button array
            buttons = []

            # Loop over all rows
            for row in self.choices:
                r = []
                # Loop over each entry
                for text in row:
                    # Append the text as a new button
                    if isinstance(text, str):
                        r.append(
                            InlineKeyboardButton(text=text,
                                                 callback_data=text))
                    else:
                        r.append(
                            InlineKeyboardButton(text=text[0],
                                                 callback_data=text[1]))

                # Append the button row to the list
                buttons.append(r)

            # Assemble keyboard
            keyboard = InlineKeyboardMarkup(inline_keyboard=buttons)

        elif self.keyboard is not None:

            # For anything except a collection, any previous sent keyboard is deleted
            if not isinstance(self.keyboard, collections.Iterable):
                keyboard = ReplyKeyboardRemove()

            else:

                # In the case of 1-dimensional array
                # align the options in pairs of 2
                if isinstance(self.keyboard[0], str):
                    self.keyboard = [[
                        y for y in self.keyboard[x * 2:(x + 1) * 2]
                    ] for x in range(int(math.ceil(len(self.keyboard) / 2)))]

                # Prepare button array
                buttons = []

                # Loop over all rows
                for row in self.keyboard:
                    r = []
                    # Loop over each entry
                    for text in row:
                        # Append the text as a new button
                        r.append(KeyboardButton(text=text))
                    # Append the button row to the list
                    buttons.append(r)

                # Assemble keyboard
                keyboard = ReplyKeyboardMarkup(keyboard=buttons,
                                               one_time_keyboard=True)
        else:
            keyboard = None

        return {
            'parse_mode':
            self.markup,
            'reply_to_message_id':
            _context.get('init_message').id if self.mark_as_answer
            and _context.get('message') is not None else None,
            'disable_web_page_preview':
            self.disable_web_preview,
            'disable_notification':
            self.disable_notification,
            'reply_markup':
            keyboard,
            'caption':
            self.caption
        }