Example #1
0
def mainFunc():
    MessageLoop(bot, handle).run_as_thread()
    print('Listening...')

    while 1:
        time.sleep(10)
Example #2
0
	def start(self):
		signal.signal(signal.SIGINT, self.sigint_handler)
		MessageLoop(self.bot, {'chat': self.handle_message, 'callback_query': self.handle_callback}).run_as_thread()
		while 1:
			time.sleep(0.007)
Example #3
0
    def IQ_find_user_ind(self, username):
        for i in range(len(self.infa_queue)):
            if self.infa_queue[i] == username:
                return i
        return -1

    def IQ_delete_user(self, username):
        del self.infa_queue[self.IQ_find_user_ind(username)]


def insertSession(ssn):
    global __SESSIONS__
    __SESSIONS__.append(ssn)


def findSessionByID(session_id):
    global __SESSIONS__
    for i in range(len(__SESSIONS__)):
        if (__SESSIONS__[i].chat_id == session_id):
            return __SESSIONS__[i]
    return session('null', -1)


random.seed(time.time())
JustBot = tp.Bot(__TOKEN__)
MessageLoop(JustBot, handle).run_as_thread()
print("JustBot started")
while 1:
    time.sleep(10)
Example #4
0
        if content_type == 'text':
            if chat_id not in users:
                this_user = User(chat_id)
                users.append(this_user)
            else:
                this_user = users[users.index(chat_id)]

            try:
                send_message = this_user.say(msg['text'], bot)

                if send_message:
                    bot.sendMessage(
                        chat_id,
                        msg_state[this_user.state.value],
                        reply_markup=rkb_state[this_user.state.value])

            except InputError:
                bot.sendMessage(chat_id,
                                err_bad_input,
                                reply_markup=rkb_state[this_user.state.value])

            except ValueError:
                bot.sendMessage(chat_id, err_val)


bot = telepot.Bot(TOKEN)
MessageLoop(bot, handle_chat).run_as_thread()

while True:
    time.sleep(30)
Example #5
0
            reply_markup=listaCall)
    elif text == "/prossimacall":
        bot.sendMessage(
            chat_id, "La prossima call comunitaria sara' quella del " +
            giornoCall + " " + meseCall + " " + annoCall +
            ", (il primo venerdi' del mese) alle ore 18:30.\nQuesta e' una stima, potrebbero esserci slittamenti o annullamenti. Per maggiore sicurezza chiedi nel gruppo Home di Mozilla Italia."
        )
    elif text == "/progetti":
        bot.sendMessage(
            chat_id,
            "Questi sono i progetti di mozilla attualmente attivi:",
            reply_markup=progetti)
        bot.sendMessage(
            chat_id,
            "Questi, invece, sono i progetti della comunità di mozilla italia:",
            reply_markup=progettimozita)
    else:
        bot.sendMessage(chat_id,
                        "Errore: comando non riconosciuto",
                        reply_markup=start)


bot = telepot.Bot(TOKEN)
MessageLoop(bot, {
    'chat': risposte,
    'callback_query': risposte
}).run_as_thread()

while 1:
    time.sleep(10)
Example #6
0
def main():

    import os
    import sys
    sys.path.append(os.path.dirname(os.path.abspath(
        os.path.dirname(__file__))))

    import datetime
    from datetime import timedelta

    import time
    import telepot
    from telepot.loop import MessageLoop

    from src import hourly_for_telegram

    # import loggingmod
    import traceback

    def start_msg():
        return '''
지역별 날씨를 예보합니다. 지역을 입력해주세요.
마침표 하나만 입력해서 이전 지역을 다시 사용할 수 있습니다.

/help 로 도움말을 볼 수 있습니다.
Bot command list:
/start
/help
/command
/about
'''

    def help_msg():
        return '''
지역별 날씨를 예보합니다. 지역을 입력해주세요.
마침표 하나만 입력해서 이전 지역을 다시 사용할 수 있습니다.

Bot command list:
/start
/help
/command
/about
'''

    def about_msg():
        return '''
Hourly Weather Bot

@telnturtle || [email protected]
'''

    def send_msg(bot, chat_id, msg):
        bot.sendMessage(chat_id, msg)
        # loggingmod.logger.info('chat_id: %s\nGMT    : %s\nKST    : %s\npayload: %s\n' % (
        #     chat_id,
        #     datetime.datetime.now().isoformat(' ')[:19],
        #     (datetime.datetime.now() + timedelta(hours=9)).isoformat(' ')[:19],
        #     msg))
        print('chat_id: %s\nGMT    : %s\nKST    : %s\npayload: %s\n' %
              (chat_id, datetime.datetime.now().isoformat(' ')[:19],
               (datetime.datetime.now() +
                timedelta(hours=9)).isoformat(' ')[:19], msg))

    def handle(msg_):
        content_type, chat_type, chat_id = telepot.glance(msg_)
        time_diff = time.time() - msg_['date']
        time_diff_limit = 60
        text = msg_['text']

        if content_type == 'text' and text.startswith('/'):
            if text == '/start':
                send_msg(bot, chat_id, start_msg())
            elif text == '/help':
                send_msg(bot, chat_id, help_msg())
            elif text == '/about':
                send_msg(bot, chat_id, about_msg())

        if content_type == 'text' and time_diff_limit > time_diff and not text.startswith(
                '/'):

            # 'Sorry, an error occurred. Please try again later.'
            NO_RESULT_MSG = '일치하는 검색결과가 없습니다.'
            payload_list = []

            try:
                payload_list = hourly_for_telegram.make_payload(chat_id,
                                                                text,
                                                                aq=True,
                                                                daily=True)
                # for weather.com only
                # payload_list[0] = (payload_list[0].replace('Rain', 'Rain☔')
                #                    .replace('Thunderstorm', 'Thunderstorm⛈')
                #                    .replace('Cloudy', 'Cloudy☁️')
                #                    .replace('Clouds', 'Clouds☁️')
                #                    .replace('Clear', 'Clear☀️')
                #                    .replace('Overcast', 'Overcast☁️'))
            except Exception as e:
                payload_list.insert(0, NO_RESULT_MSG)
                # loggingmod.logger.error(e, exc_info=True)
                traceback.print_exc()

            send_msg(bot, chat_id, payload_list[0])
            for msg_ in payload_list[
                    1:] if payload_list[0] != NO_RESULT_MSG else []:
                send_msg(bot, chat_id, msg_)

    with open(
            os.path.join(os.path.dirname(os.path.abspath(__file__)), '..',
                         'rsc', '_keys', 'keys'), 'r') as f:
        TOKEN = f.readlines()[9][:-1]

    bot = telepot.Bot(TOKEN)
    _count = 5
    while 1:
        try:
            MessageLoop(bot, handle).run_as_thread(allowed_updates='message')
            # loggingmod.logger.info('Listening ...')
            print('Listening ...')
            while 1:
                time.sleep(5)
        except Exception as e:
            # loggingmod.logger.error(e, exc_info=True)
            traceback.print_exc()

        _count = _count - 1
        if _count < 1:
            break

    # Keep the program running.
    while 1:
        time.sleep(10)
Example #7
0
            else:
                reply = 'Can\'t find answer to your response'
                bot.sendMessage(user_id, reply)
     

        elif len(Message_list.intersection(sending_picture))>1:
            bot.sendPhoto(user_id, photo=open('picture.png', 'rb'))

        elif len(Message_list.intersection(sending_audio))>1:
            bot.sendAudio(user_id, audio = open('fracture.mp3', 'rb'))

        elif len(Message_list.intersection(sending_video))>1:
            bot.sendVideo(user_id, video = open('cars.mp4', 'rb'))

        elif len(Message_list.intersection(sending_document))>1:
            bot.sendDocument(user_id, document =open('knowledge.json', 'rb'))

        else:
            reply = 'Sorry didn\'t understand it \n can you rephrase it in another short way'
            bot.sendMessage(user_id, reply)       
        
def sending_message():
    for user in active_user_id:
        quote = random_quote()
        bot.sendMessage(user, quote)        

MessageLoop(bot, check_new).run_as_thread()

while True:
    time.sleep(10)
    sending_message()
Example #8
0
def run_bot():
    MessageLoop(bot, {'chat':handler, 'callback_query':daily_feedback1}).run_as_thread()
    while 1:
        time.sleep(10)
Example #9
0
    categoriesdb = CategoriesDB.CategoriesDB()
    mediavotedb = MediaVoteDB.MediaVoteDB()

    # clean up mess

    for category in categoriesdb.getValues():
        if category.creator not in usersdb.database.keys():
            print("found stray category")

    log.info("Loaded databases")
    try:
        response = {
            'chat': handle,
            'callback_query': query,
            'inline_query': inline_query,
            'chosen_inline_result': chosen_inline
        }

        MessageLoop(bot, response).run_as_thread()
    except Exception as e:
        log.exception("main: Big mistake")

    log.info("Message loop started")

    routine = Routine.Routine()
    routine.run_routine_func(usersdb, mediavotedb, categoriesdb)

    log.info("Routine started")

    while 1:
        time.sleep(10)
Example #10
0
    elif targetName in players[username].hasreport:
        bot.sendMessage(chatId, "你要讓他死嗎?")

    else:
        players[username].hasreport.append(targetName)
        players[targetName].bereport += 1
        bot.sendMessage(chatId, targetName + "被檢舉了")
        if players[targetName].bereport >= howManyPlayer // 2:
            # deleteplayer(chatId,targetName)
            deleterecord(targetName)
            deletereport(msg, chatId, targetName)


MessageLoop(bot, {
    'chat': handle,
    'callback_query': on_callback_query
}).run_as_thread()  #等候輸入
message_with_inline_keyboard = None
keyboards = []
chatId = 0
players = {}  #@username player
Hints = []
usernamedata = []
howManyPlayer = 0
howmanyundercover = 0
undercover = []
canjoin = True
HintRound = False
canvote = True
isButtonTime = True
canNewgame = True
Example #11
0
                'Leider ist dein Befehl nicht in der Datenbank verzeichnet.\n Hier nochmal deine Möglichkeiten:\n\n --- Image image_number --- \n Hier erhälst du das Bild mit der Nummer image_number direkt auf dein Handy geschickt.\n Bsp: Image 7\n Um Bildnummer 7 zuerhalten. \n\n --- Stat keyword ---\n Hier erhälst du verschiedene Nutzerstatistiken der Photobox. Als Keyword stehen zur Verfügung:\n name, popular, timebased und taken.\nBsp:\n stat name \n\n --- Help ---\n Hier wird Steven auf seinem Handy benachrichtigt und kommt schnellstmöglichst zu dir. Wenn er nicht kommt solltest du ihn suchen gehen.'
            )


### Start Photobox if used as main class

if __name__ == '__main__':
    piBot = tp.Bot(get_ID())
    piphotobox = PiPhotobox('admin_id.txt')

    os.chdir("/media/pi/Marten/photo_folder")

    try:

        MessageLoop(
            piBot,
            piphotobox.send_image).run_as_thread()  # Start the Telegramm chat
        print('start')
        while True:
            time.sleep(1)

    except KeyboardInterrupt:
        print('Programm wird beendet')
        piphotobox.end_connection()

###
# Implementierung der User_Stats Database
# Einfügen der Funktionen
# Einfügen einer KeyboardInterrupt Funtkion
# Einfügen der FotoDatabase
# mehr try Funktionen
Example #12
0
from telepot.loop import MessageLoop

now = dtime.datetime.now()
updateid=0

def test(msg):

      chat_id = msg['chat']['id']
      command = msg['text']      
      print('Naricht erkannt')

      if command == '/test':
            response= piBot.getUpdates()
            #print(response['message']['from']['username'])
            print(msg['chat']['username'])
            piBot.sendMessage(chat_id,str('TEST NARICHT') )

      if command == 'name':
            user_id=msg['id']
            user_name


piBot = tp.Bot('533241039:AAHWKO_Iobo665OK-ffCKqW80Q6RiU4yFpM')
MessageLoop(piBot, test).run_as_thread()

print('Start')

while True:
      
      time.sleep(1)
Example #13
0
 def run(self):
     print('Running Jarvis...')
     MessageLoop(self.bot_api, handle=self.handle_message).run_as_thread()
Example #14
0
def fetch():
    print("Howdy")
    MessageLoop(bot, handle).run_forever()
    print('Listening ...')
Example #15
0
        chat_id = message["message"]["chat"]["id"]
        message_text = json.loads(message["data"])['name']
    else:
        chat_id = message["chat"]["id"]
        bot.sendMessage(chat_id, MESSAGE_ERROR)
        return

    if state == 'normal':
        if message_text == "/start":
            bot.sendMessage(chat_id, MESSAGE_START, reply_markup=KEYBOARD_START)
        if message_text == 'menu':
            bot.sendMessage(chat_id, MESSAGE_MENU, reply_markup=KEYBOARD_MENU)
        if message_text == 'categories':
            bot.sendMessage(chat_id, MESSAGE_CATEGORIES, reply_markup=get_categories_menu())
        if message_text == 'add_category':
            state = 'add_category'
            bot.sendMessage(chat_id, MESSAGE_ADD_CATEGORY)
        if message_text == 'get_category':
            category = json.loads(message["data"])['data']
            bot.sendMessage(chat_id, category['name'], reply_markup=get_category_menu(category['id']))
    elif state == 'add_category':
        state = 'normal'
        text = add_category(message_text)
        bot.sendMessage(chat_id, text, reply_markup=get_categories_menu())


# цикл приема сообщений
loop = asyncio.get_event_loop()
loop.create_task(MessageLoop(bot, handle).run_forever())
loop.run_forever()
Example #16
0
def onCallbackQuery(msg):  # Função de ação do botão de baixar
    queryID, chatid, queryData = glance(msg, flavor='callback_query')
    bot.answerCallbackQuery(queryID,
                            text='Seu arquivo MP3 está sendo preparado')
    Util.baixarMP3(resultado[int(queryData)])
    bot.sendMessage(
        chatid,
        emojize('Sua música já está sendo enviada... :headphones:',
                use_aliases=True))
    bot.sendChatAction(chatid, 'upload_audio')
    arq = Util.pegaMP3()
    bot.sendAudio(
        chatid, open(arq, 'rb'),
        title=arq[:len(arq) -
                  16])  # manda a música com apenas seu nome original sem url
    sleep(5)
    from os import remove
    remove(arq)
    print(f'Baixar {arq[:len(arq) - 16]}')  # Nome do áudio baixado para o log


MessageLoop(bot, {
    'chat': onChatMessage,
    'callback_query': onCallbackQuery
}).run_as_thread()
print(bot.getMe())
print('Escutando ...')

while True:
    pass
Example #17
0
    print("    status:", user.status)
    print("    question:", user.question)
    # 聊天種類
    print("😎 CHAT")
    print("    type:", msg['chat']['type'])
    if msg['chat']['type'] != 'private':
        print("    title:", msg['chat']['title'])
    # 使用者傳送文字
    if 'text' in msg:
        print("😯 TEXT")
        print("    text:", msg['text'])
    if 'caption' in msg:
        print("😯 TEXT")
        print("    text: ", msg['caption'])
    # 使用者傳送檔案
    if 'document' in msg:
        print("😠 DOCUMENT")
        print("    file_name:", msg['document']['file_name'])
        print("    file_id:", msg['document']['file_id'])


# 開始執行
MessageLoop(bot, on_chat).run_as_thread()
print("Started! Service is available.")

while True:
    time.sleep(60)

    # 定期敲 Telegram 讓 Bot 不要死掉
    bot.getMe()
Example #18
0
            # /ac <username> <task_number>
            elif command[:2] == "ac":
                data = command[2:].split()
                userteam = self[data[0][1:]]["team"]
                if username in admins_list:
                    if data[1] in team[userteam]:
                        if team[userteam][data[1]] == True:
                            bot.sendMessage(header[2], "You have accepted.")
                        else:
                            team[userteam][data[1]] = True
                            team[userteam]["total"] += task[data[1]]['score']
                            bot.sendMessage(
                                header[2], "Congratulations! team " +
                                userteam + " send the correct answer!")
                    else:
                        team[userteam][data[1]] = True
                        team[userteam]["total"] += task[data[1]]['score']
                        bot.sendMessage(
                            header[2], "Congratulations! team " +
                            str(userteam) + " send the correct answer!")


MessageLoop(
    bot,
    {
        'chat': on_chat,
        #'callback_query': on_callback_query,
    }).run_as_thread()

print('Listening ...')
 def setTalkHandleFunction(self, handle):
     MessageLoop(self.wrBot, handle).run_as_thread()
        studyTime= studyTime+60
        totalStudyTime[from_id] = totalStudyTime[from_id] + 60

    else:
        
        module[from_id][query_data]= module[from_id][query_data]+ studyTime
        
        response= str(query_data)+ " selected."

        



    bot.sendMessage(from_id, response) 
    bot.answerCallbackQuery(query_id)

    return
    
    

    
TOKEN = ''
bot = telepot.Bot(TOKEN)

MessageLoop(bot,{'chat': main, 'callback_query': on_callback_query}).run_as_thread()
print("listening")

while 1:
    time.sleep(10)
    bot_pulse()
Example #21
0
            elif command_tokens[0] in ('/help', '/help@sybilforkbot'):
                self.sender.sendMessage(
                    "All commands are prefixed by a forward slash (/), with no spaces between the"
                    +
                    " slash and your command. Dealt cards remain out of the deck until you issue a 'Majors', 'Minors', "
                    + "'Full', 'Settype', or 'Shuffle' command.\n " +
                    "These are the commands I currently understand:\n\n" +
                    "Majors -- Set deck to deal only from the Major Arcana\n" +
                    "Minors -- Set deck to deal only the pips\n" +
                    "Full -- Set deck to deal both Majors and Minors\n" +
                    "Listtypes -- List the types of decks available for use\n"
                    +
                    "Settype [type] -- Sets to one of the decks listed in Listtypes, eg: /settype "
                    + "jodocamoin Note: This reshuffles the deck\n" +
                    "Draw -- Draw a card\n" + "Help -- This text\n")
        redis.set(from_id, pickle.dumps(self.deck))


if __name__ == '__main__':
    token = sys.argv[1]
    setup_logger('sybil')
    logging.info('Starting bot with token {}'.format(token))
    redis = redis.StrictRedis(host='localhost', port=6379, db=0)
    sybil = telepot.DelegatorBot(
        token,
        [pave_event_space()(per_chat_id(), create_open, Sybil, timeout=600)])
    logging.info('Waiting for messages')
    MessageLoop(sybil).run_as_thread()
    while 1:
        time.sleep(1)
            GPIO.output(Relay2,1)
            message=message + " Relay2"
        #print(chat_id)
        telegram_bot.sendMessage(chat_id, message)
        
        
def scrape():# Function for scraping the news website for getting the headlines
    news=[]
    url = "https://www.indiatoday.in/news.html"  # url of website that we want to scrape
    res=requests.get(url)
    code=BeautifulSoup(res.text,"lxml")
    head=code.find_all("p",class_="story")
    for i in range(0,10):
        news.append(str(head[random.randint(0,len(head))-1].text))
    return news #returns list of headlines in the website


telegram_bot=telepot.Bot("******************************************")#API Key you get from the bot-father in telegram app

print(telegram_bot.getMe())


MessageLoop(telegram_bot,action).run_as_thread()
print("started and running")



while True:
    time.sleep(1000)

Example #23
0
        return articles

    answerer.answer(msg, compute)


def on_chosen_inline_result(msg):
    result_id, from_id, query_string = telepot.glance(
        msg, flavor='chosen_inline_result')
    print('Chosen Inline Result:', result_id, from_id, query_string)


telegram_bot = telepot.Bot('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')
# print(telegram_bot.getMe())
logging.info(telegram_bot.getMe())
telegram_bot.sendMessage(896631342,
                         str('*Pi03 Started.*'),
                         parse_mode="Markdown")
answerer = telepot.helper.Answerer(telegram_bot)

# MessageLoop(telegram_bot, action).run_as_thread()
MessageLoop(telegram_bot, {
    'chat': on_chat_message,
    'callback_query': on_callback_query
}).run_as_thread()

# MessageLoop(telegram_bot, {'inline_query': on_inline_query, 'chosen_inline_result': on_chosen_inline_result}).run_as_thread()

while 1:
    time.sleep(10)
Example #24
0
    elif content_type == 'photo':
        baixarFotos(bot, msg, chat_id, FLAG)
        FLAG = None if FLAG is not None else FLAG
    else:
        bot.sendMessage(chat_id, 'Você não tem autorização!!!')
        bot.sendMessage(chat_id,
                        """
Caso queira testar, envie uma menssagem para 
@ColdMaster - Menino do designer e Banco de dados.
@Renanzx - Ué, Isso não vai funcionar, talvez funcione.
@lucasnasm - Read the docs



Orgulhosamente em fase beta!!!
""",
                        parse_mode='Markdown')


if __name__ == "__main__":
    verifica_db()
    verifica_pastas()
    MessageLoop(bot, corpo).run_as_thread()
    print 'Rodando...'
    while 1:
        try:
            time.sleep(10)
        except KeyboardInterrupt:
            fecha_conexao()
            exit(0)
Example #25
0
            self._state_input = 'addservice_migrasi_modifikasi'
        elif query_data == 'addservice':
            self._cancel_markup()
            self._send_message('Masukkan nomor pelanggan.')
            self._state_input = 'addservice'

        elif query_data == 'unbind':
            unbind = db.unbind(from_id)
            self._send_message('Unbind berhasil.', self.daftar_keyboard)
            self._state = ''


# TOKEN = sys.argv[1]  # get token from command-line
if sys.version[0] == '3':
    # @developmentdamanbot
    TOKEN = '694699130:AAG4S3Tb9uxxxPHjbl5fP-QiNsjOehOhieM'
else:
    # @haeventbot
    TOKEN = '692089019:AAHR_d7I0VRer2BELku90RHlzP6m7fp14DY'

bot = telepot.DelegatorBot(TOKEN, [
    include_callback_query_chat_id(pave_event_space())(
        per_chat_id(), create_open, HadirEvent, timeout=500),
])

MessageLoop(bot).run_as_thread()
print('Listening ...')

while 1:
    time.sleep(10)
Example #26
0
                    id=res,
                    title=res,
                    input_message_content=InputTextMessageContent(
                        message_text=res)))

        return articles

    answerer.answer(msg, compute)


def on_chosen_inline_result(msg):
    result_id, from_id, query_string = telepot.glance(
        msg, flavor='chosen_inline_result')
    print('Chosen Inline Result:', result_id, from_id, query_string)


bot = telepot.Bot(private.token)
answerer = telepot.helper.Answerer(bot)

MessageLoop(
    bot, {
        'chat': on_chat_message,
        'inline_query': on_inline_query,
        'chosen_inline_result': on_chosen_inline_result
    }).run_as_thread()

print 'I am listening ...'

while 1:
    time.sleep(10)
Example #27
0
    keyboard = InlineKeyboardMarkup(inline_keyboard=[
        [InlineKeyboardButton(text='Press me', callback_data='press')],
    ])


def inline_query():
    print("Query Inline")
    bot_results = client(GetInlineBotResultsRequest(bot, mychat, '', ''))

    if bot_results.results:
        query_id = bot_results.query_id
        # choose a result from the list
        result_id = getResultId(bot_results.results)
        client(SendInlineBotResultRequest(mychat, query_id, result_id))
        #return True

    else:
        print(bot_results)
        #return None


MessageLoop(bot, {
    'chat': on_chat_message,
    'callback_query': inline_query
}).run_as_thread()

print('Listening ...')

while 1:
    time.sleep(10)
Example #28
0
    gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
    faces = classifier.detectMultiScale(gray, 1.3, 5)
    count = 0
    for (x, y, w, h) in faces:
        count = count + 1
        cv.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 5)
    return image, count


def handle(msg):
    # pprint.pprint(msg)
    if msg["photo"]:
        chat_id = msg['chat']['id']
        f = tempfile.NamedTemporaryFile(delete=True).name + ".png"
        photo = msg['photo'][-1]["file_id"]
        path = bot.getFile(photo)["file_path"]
        # bot.sendMessage(chat_id, "Retrieving %s" % path)
        bot.download_file(photo, f)
        p = cv.imread(f)
        hsv, l = detect(p)
        cv.imwrite(f, hsv)
        bot.sendMessage(chat_id, "found %i faces" % l)
        bot.sendPhoto(chat_id, open(f, 'rb'))
        # print("photo sent")
    else:
        print("no photo")


bot = telepot.Bot(os.environ["BOT_TOKEN"])
MessageLoop(bot, handle).run_forever()
Example #29
0
                'comando não compreendido. \n comandos possíveis: FOTO RED GREEN BLUE OFF FEED INFO STATUS'
            )


def rc_time(pin_to_circuit):
    count = 0
    GPIO.setup(pin_to_circuit, GPIO.OUT)
    GPIO.output(pin_to_circuit, GPIO.LOW)
    time.sleep(0.1)
    GPIO.setup(pin_to_circuit, GPIO.IN)
    while (GPIO.input(pin_to_circuit) == GPIO.LOW):
        count += 1
    return count


MessageLoop(bot, handle).run_as_thread()

fishes = [(1, 1, 1, 1)]
while True:
    try:
        _, img = cap.read()
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        try:
            fishes = fish_cascade.detectMultiScale(gray)
        except:
            pass
        for (x, y, w, h) in fishes:
            if (w < 70 and w > 2 and h > 2):
                cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 1)
        cv2.putText(img,
                    ("%s %s %s %s %s %s" %
Example #30
0
                value = message.split('|')
                user_text = value[0]
                user_dest = value[-1].strip()
                translator = Translator()
                translations = translator.translate(
                    f'{user_text}', dest=f'{user_dest}')
                user_dest_name = LANGUAGES[user_dest]
                user_src_name = LANGUAGES[translations.src]
                bot.sendChatAction(chat_id, 'typing')
                bot.sendMessage(
                    chat_id, f'From <b>{user_src_name}</b> to <b>{user_dest_name}</b>', parse_mode='html')
                bot.sendMessage(
                    chat_id, f'<b>{translations.text}</b>', parse_mode='html')
            except ValueError:
                bot.sendMessage(
                    chat_id, f'invalid destination! what does {user_dest} means see How does it works section!')


# get token from command-line
TOKEN = '1239352593:AAHOZkDwqlkgeyWAb6kjOPxlphQgWKGaJsw'

bot = telepot.Bot(TOKEN)
answerer = telepot.helper.Answerer(bot)

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

# Keep the program running.
while 1:
    time.sleep(10)