def handle(msg):
    flavor = telepot.flavor(msg)

    # normal message
    if flavor == "normal":
        content_type, chat_type, chat_id = telepot.glance2(msg)
        print("Normal Message:", content_type, chat_type, chat_id)

        # Do your stuff according to `content_type` ...

    # inline query - need `/setinline`
    elif flavor == "inline_query":
        query_id, from_id, query_string = telepot.glance2(msg, flavor=flavor)
        print("Inline Query:", query_id, from_id, query_string)

        # Compose your own answers
        articles = [{"type": "article", "id": "abc", "title": "ABC", "message_text": "Good morning"}]

        yield from bot.answerInlineQuery(query_id, articles)

    # chosen inline result - need `/setinlinefeedback`
    elif flavor == "chosen_inline_result":
        result_id, from_id, query_string = telepot.glance2(msg, flavor=flavor)
        print("Chosen Inline Result:", result_id, from_id, query_string)

        # Remember the chosen answer to do better next time

    else:
        raise telepot.BadFlavor(msg)
示例#2
0
def handle(msg):
    flavor = telepot.flavor(msg)

    # a normal message
    if flavor == 'normal':
        content_type, chat_type, chat_id = telepot.glance2(msg)
        print content_type, chat_type, chat_id

        # Do your stuff according to `content_type` ...

    # an inline query - only AFTER `/setinline` has been done for the bot.
    elif flavor == 'inline_query':
        query_id, from_id, query_string = telepot.glance2(msg, flavor=flavor)
        print 'Inline Query:', query_id, from_id, query_string

        # Compose your own answers
        articles = [{'type': 'article',
                        'id': 'abc', 'title': 'ABC', 'message_text': 'Good morning'}]

        bot.answerInlineQuery(query_id, articles)

    # a chosen inline result - only AFTER `/setinlinefeedback` has been done for the bot.
    elif flavor == 'chosen_inline_result':
        result_id, from_id, query_string = telepot.glance2(msg, flavor=flavor)
        print 'Chosen Inline Result:', result_id, from_id, query_string

        # Remember the chosen answer to do better next time

    else:
        raise telepot.BadFlavor(msg)
示例#3
0
    def handle(self, msg):
        flavor = telepot.flavor(msg)

        # normal message
        if flavor == 'normal':
            content_type, chat_type, chat_id = telepot.glance2(msg)
            print('Normal Message:', content_type, chat_type, chat_id)

            # Do your stuff according to `content_type` ...

        # inline query - need `/setinline`
        elif flavor == 'inline_query':
            query_id, from_id, query_string = telepot.glance2(msg, flavor=flavor)
            print('Inline Query:', query_id, from_id, query_string)

            # Compose your own answers
            articles = [{'type': 'article',
                            'id': 'abc', 'title': 'ABC', 'message_text': 'Good morning'}]

            bot.answerInlineQuery(query_id, articles)

        # chosen inline result - need `/setinlinefeedback`
        elif flavor == 'chosen_inline_result':
            result_id, from_id, query_string = telepot.glance2(msg, flavor=flavor)
            print('Chosen Inline Result:', result_id, from_id, query_string)

            # Remember the chosen answer to do better next time

        else:
            raise telepot.BadFlavor(msg)
示例#4
0
def answer(msg):
    flavor = telepot.flavor(msg)

    if flavor == "inline_query":
        query_id, from_id, query = telepot.glance2(msg, flavor=flavor)

        if from_id != USER_ID:
            print "Unauthorized user:"******"InlineQuery")

        articles = [
            InlineQueryResultArticle(
                id="abc", title="HK", message_text="Hong Kong", url="https://www.google.com", hide_url=True
            ),
            {"type": "article", "id": "def", "title": "SZ", "message_text": "Shenzhen", "url": "https://www.yahoo.com"},
        ]

        photos = [
            InlineQueryResultPhoto(
                id="123",
                photo_url="https://core.telegram.org/file/811140934/1/tbDSLHSaijc/fdcc7b6d5fb3354adf",
                thumb_url="https://core.telegram.org/file/811140934/1/tbDSLHSaijc/fdcc7b6d5fb3354adf",
            ),
            {
                "type": "photo",
                "id": "345",
                "photo_url": "https://core.telegram.org/file/811140184/1/5YJxx-rostA/ad3f74094485fb97bd",
                "thumb_url": "https://core.telegram.org/file/811140184/1/5YJxx-rostA/ad3f74094485fb97bd",
                "caption": "Caption",
                "title": "Title",
                "message_text": "Message Text",
            },
        ]

        results = random.choice([articles, photos])

        bot.answerInlineQuery(query_id, results)

    elif flavor == "chosen_inline_result":
        result_id, from_id, query = telepot.glance2(msg, flavor=flavor)

        if from_id != USER_ID:
            print "Unauthorized user:"******"ChosenInlineResult")

        print "Chosen inline query:"
        pprint.pprint(msg)

    else:
        raise telepot.BadFlavor(msg)
示例#5
0
    def handle(self, msg):
        flavor = telepot.flavor(msg)

        # a normal message
        if flavor == 'normal':
            content_type, chat_type, chat_id = telepot.glance2(msg)
            print(content_type, chat_type, chat_id)

            # Do your stuff according to `content_type` ...

        # an inline query - possible only AFTER `/setinline` has been done for the bot.
        elif flavor == 'inline_query':
            query_id, from_id, query_string = telepot.glance2(msg, flavor=flavor)
            print(query_id, from_id, query_string)
示例#6
0
def handle(msg):
    flavor = telepot.flavor(msg)
    # normal message
    if flavor == 'normal':
        content_type, chat_type, chat_id = telepot.glance2(msg)
        print('Normal Message:', content_type, chat_type, chat_id)
        command = msg['text']
        if command == '/start':
        	start(chat_id)
        elif command == '/eagles':
        	news_command_handler(chat_id, 'eagles')
        elif command == '/flyers':
        	news_command_handler(chat_id, 'flyers')
        elif command == '/sixers':
        	news_command_handler(chat_id, 'sixers')
        elif command == '/phillies':
        	news_command_handler(chat_id, 'phillies')
        elif command == '/help':
        	help(chat_id)
        elif command == '/settings':
        	settings(chat_id)
        else:
        	unknown(chat_id)

        return('Message sent')

        # Do your stuff according to `content_type` ...

    # inline query - need `/setinline`
    elif flavor == 'inline_query':
        query_id, from_id, query_string = telepot.glance2(msg, flavor=flavor)
        print('Inline Query:', query_id, from_id, query_string)

        # Compose your own answers
        articles = [{'type': 'article',
                        'id': 'abc', 'title': 'ABC', 'message_text': 'Good morning'}]

        bot.answerInlineQuery(query_id, articles)

    # chosen inline result - need `/setinlinefeedback`
    elif flavor == 'chosen_inline_result':
        result_id, from_id, query_string = telepot.glance2(msg, flavor=flavor)
        print('Chosen Inline Result:', result_id, from_id, query_string)

        # Remember the chosen answer to do better next time

    else:
        raise telepot.BadFlavor(msg)
示例#7
0
文件: factors.py 项目: nsreehari/bots
    def on_message(self, msg):
        content_type, chat_type, chat_id = telepot.glance2(msg)

        if content_type != 'text':
            self.sender.sendMessage('Give me two numbers, please.')
            return

        try:
            m = msg['text'].strip().split()
            m1 = int(m[0])
            m2 = int(m[1])
            if len(m) > 2:
                raise ValueError
        except :
            self.sender.sendMessage('Give two numbers correctly, please.')
            return

        # check the guess against the answer ...
        if m1 * m2 != self._answer:
            # give a descriptive hint
            hint = self._hint(self._answer, m1, m2)
            self.sender.sendMessage(hint)
        else:
            self.sender.sendMessage('Correct!')
            self.close()
示例#8
0
def see_every_content_types(msg):
    global expected_content_type, content_type_iterator

    flavor = telepot.flavor(msg)

    if flavor == 'normal':
        content_type, chat_type, chat_id = telepot.glance2(msg)
        from_id = msg['from']['id']

        if chat_id != USER_ID and from_id != USER_ID:
            print 'Unauthorized user:'******'Message')
        try:
            if content_type == expected_content_type:
                expected_content_type = content_type_iterator.next()
                bot.sendMessage(chat_id,
                                'Please give me a %s.' % expected_content_type)
            else:
                bot.sendMessage(
                    chat_id, 'It is not a %s. Please give me a %s, please.' %
                    (expected_content_type, expected_content_type))
        except StopIteration:
            # reply to sender because I am kicked from group already
            bot.sendMessage(from_id, 'Thank you. I am done.')

    else:
        raise telepot.BadFlavor(msg)
示例#9
0
文件: smallbot.py 项目: AWilcke/uAI
def handle_message(msg):
    global active, bigrams, trigrams, weight, aB, aT, aW, mB, mT, mW, tB, tT, tW
    msg_type, chat_type, chat_id = telepot.glance2(msg)
    if msg_type != 'text':
        return
    input = msg['text']
    reply_id = chat_id
    if "/changebot_first" in input and active!='first':
        bigrams, trigrams, weight = aB, aT, aW
        active = 'first'
        print "first loaded"
        bot.sendMessage(reply_id, "first bot here")

    elif "/changebot_second" in input and active!='second':
        bigrams, trigrams, weight = mB, mT, mW
        active = 'second'
        print "second loaded"
        bot.sendMessage(reply_id, "second bot here")

    elif "/changebot_third" in input and active!='third':
        bigrams, trigrams, weight = tB, tT, tW
        active = 'third'
        print "third loaded"
        bot.sendMessage(reply_id, "third bot here")

    else:
        try:
            bot.sendMessage(reply_id, genSentence(input, weight, bigrams, trigrams))
        except:
            bot.sendMessage(reply_id, "U WOT M8?")
示例#10
0
def insertBirthday(msg):
	# Parse info from message
	content_type, chat_type, chat_id = telepot.glance2(msg)

	# Open BD of the group
	birthdayBD = shelve.open("BD" + str(chat_id))

	# Stores user name
	userName = msg['from']['first_name'] + " " + msg['from']['last_name']

	# Stores original message
	command = msg['text'].split(' ')

	if(len(command) == 3):
		try:
			day = int(command[1])
			month = int(command[2])
		except TypeError:
			print("Can't convert string to int")
			return 0

		if(day > 0 and day <= 31 and month > 0 and month <= 12):
			birthdayBD[str(msg['from']['id'])] = [userName, day, month]
			birthdayBD.close()
			bot.sendMessage(chat_id, "Birthday stored.")
			updateScheduler()
	else:
		bot.sendMessage(chat_id, "Bad formating, try again using '/bday dd mm' \ndd = day \nmm = month ")

	return 0
示例#11
0
    def on_message(self, msg):
        content_type, chat_type, chat_id = telepot.glance2(msg)

        if content_type != 'text':
            self.sender.sendMessage('Give me two numbers, please.')
            return

        try:
            m = msg['text'].strip().split()
            m1 = int(m[0])
            m2 = int(m[1])
            if len(m) > 2:
                raise ValueError
        except:
            self.sender.sendMessage('Give two numbers correctly, please.')
            return

        # check the guess against the answer ...
        if m1 * m2 != self._answer:
            # give a descriptive hint
            hint = self._hint(self._answer, m1, m2)
            self.sender.sendMessage(hint)
        else:
            self.sender.sendMessage('Correct!')
            self.close()
示例#12
0
def handle(msg):
	content_type, chat_type, chat_id = telepot.glance2(msg)
	
	chat_id = msg['chat']['id']
	command = msg['text']

	if '@' in command:
		command, botname = command.split('@')
	
	command = command.replace("/", "")
        
        if command == "start":
            bot.sendMessage(chat_id, "Send /rrr to see if the RRR summerbar is currently open.\nAlso don't slap pandas 🐼")

        if command.lower() == 'rrr':
            url = "https://afternoondelight.de/rrr/status"
            page = urllib.urlopen(url).read()
            data = json.loads(page)
            #print(data["status"])
            if data["status"] == "closed":
                bot.sendMessage(chat_id, "RRR is closed")
            elif data["status"] == "open":
                bot.sendMessage(chat_id, "RRR is open")
            else:
	        bot.sendMessage(chat_id, "something's wrong...")
示例#13
0
def answer(msg):
    flavor = telepot.flavor(msg)

    if flavor == 'inline_query':
        query_id, from_id, query = telepot.glance2(msg, flavor=flavor)

        if from_id != USER_ID:
            print 'Unauthorized user:'******'InlineQuery')
        
        articles = [InlineQueryResultArticle(
                       id='abc', title='HK', message_text='Hong Kong', url='https://www.google.com', hide_url=True),
                   InlineQueryResultArticle(
                       id='def', title='SZ', message_text='Shenzhen', url='https://www.yahoo.com')]

        photos = [InlineQueryResultPhoto(
                      id='123', photo_url='https://core.telegram.org/file/811140934/1/tbDSLHSaijc/fdcc7b6d5fb3354adf', thumb_url='https://core.telegram.org/file/811140934/1/tbDSLHSaijc/fdcc7b6d5fb3354adf'),
                  {'type': 'photo',
                      'id': '345', 'photo_url': 'https://core.telegram.org/file/811140184/1/5YJxx-rostA/ad3f74094485fb97bd', 'thumb_url': 'https://core.telegram.org/file/811140184/1/5YJxx-rostA/ad3f74094485fb97bd', 'caption': 'Caption', 'title': 'Title', 'message_text': 'Message Text'}]
        """"           
        gifs = [InlineQueryResultGif(
                    id='ghi', gif_url='http://www.animalstown.com/animals/g/gnu/coloring-pages/gnu-color-page-6.gif', thumb_url='http://www.animalstown.com/animals/g/gnu/coloring-pages/gnu-color-page-6.gif'),
                {'type': 'gif',
                    'id': 'jkl', 'gif_url': 'http://img2.colorirgratis.com/gnu-na-savana-africana_49d5b597bc78d-p.gif', 'thumb_url': 'http://img2.colorirgratis.com/gnu-na-savana-africana_49d5b597bc78d-p.gif'}]
        """
#                   InlineQueryResultVideo(
#                       id='jkl', video_url='', mime_type='')

        results = random.choice([articles, photos])

        bot.answerInlineQuery(query_id, results, cache_time=20, is_personal=True, next_offset='5')
    else:
        raise telepot.BadFlavor(msg)
示例#14
0
def see_every_content_types(msg):
    global expected_content_type, content_type_iterator

    flavor = telepot.flavor(msg)

    if flavor == "normal":
        content_type, chat_type, chat_id = telepot.glance2(msg)
        from_id = msg["from"]["id"]

        if chat_id != USER_ID and from_id != USER_ID:
            print "Unauthorized user:"******"Message")
        try:
            if content_type == expected_content_type:
                expected_content_type = content_type_iterator.next()
                bot.sendMessage(chat_id, "Please give me a %s." % expected_content_type)
            else:
                bot.sendMessage(
                    chat_id,
                    "It is not a %s. Please give me a %s, please." % (expected_content_type, expected_content_type),
                )
        except StopIteration:
            # reply to sender because I am kicked from group already
            bot.sendMessage(from_id, "Thank you. I am done.")

    else:
        raise telepot.BadFlavor(msg)
示例#15
0
def handle(msg):
    content_type, chat_type, chat_id = telepot.glance2(msg)
    m = telepot.namedtuple.namedtuple(msg, 'Message')

    if chat_id < 0:
        # group message
        logger.info('Received a %s from %s, by %s' % (content_type, m.chat, m.from_))
    else:
        # private message
        logger.info('Received a %s from %s' % (content_type, m.chat))  # m.chat == m.from_

    if content_type == 'text':
        if msg['text'] == '/start':
            yield from bot.sendMessage(chat_id,  # Welcome message
                                       "You send me an Emoji"
                                       "\nI give you the Unicode"
                                       "\n\nOn Python 2, remember to prepend a 'u' to unicode strings,"
                                       "e.g. \U0001f604 is u'\\U0001f604'")
            return

        reply = ''

        # For long messages, only return the first 10 characters.
        if len(msg['text']) > 10:
            reply = 'First 10 characters:\n'

        # Length-checking and substring-extraction may work differently 
        # depending on Python versions and platforms. See above.

        reply += msg['text'][:10].encode('unicode-escape').decode('ascii')

        logger.info('>>> %s', reply)
        yield from bot.sendMessage(chat_id, reply)
示例#16
0
def handle(msg):
    print "Handle funct"
    content_type, chat_type, chat_id = telepot.glance2(msg)
    data = open("users.txt", "a")
    if str(chat_id) in open('users.txt').read():
        print "User exists"
    else:
        data.write(str(chat_id) + " ")
        data.write(
            str(msg['chat']['first_name']) + " " +
            str(msg['chat']['last_name']) + "\n")
    cmd = str(msg['text'])

    if cmd == 'Results':
        bot.sendMessage(chat_id, "Enter USN number to see your results.")

    elif len(cmd) == 10:
        bot.sendMessage(chat_id, "Processing")
        go("http://results.vtu.ac.in/")
        formclear('1')
        fv("1", "rid", cmd)
        submit('submit')
        save_html(cmd + ".html")
        lines = open(cmd + '.html').readlines()
        open(cmd + '.html', 'w').writelines(lines[241:-84])
        open(cmd + '.html', 'a').writelines(
            "@vtu_bot- if this file is empty please check the USN or try again when the results are announced "
        )
        f = open(cmd + '.html', 'rb')
        response = bot.sendDocument(chat_id, f)
    else:
        bot.sendMessage(chat_id, "Please enter a valid USN number")
def handle(msg):
	global user_state
# 	pprint.pprint(msg)
	content_type, chat_type, chat_id = telepot.glance2(msg)
	validUser = False

	# Only respond valid users
	for user in user_ids:
		if chat_id == user:
			validUser = True
		
	if validUser == False:
		return

	# Ignore non-text message
	if content_type != 'text':
		return

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

	if command[0] == '/start':
		showMainKeyboard(chat_id, user_state)
	elif command[0] == '/close':
		hide_keyboard = {'hide_keyboard': True}
		bot.sendMessage(chat_id, 'Closing light control', reply_markup=hide_keyboard)
	else:
		lights(chat_id, command[0])
示例#18
0
    def on_message(self, msg):
        flavor = telepot.flavor(msg)

        if flavor == 'inline_query':
            query_id, from_id, query_string = telepot.glance2(msg, flavor=flavor)
            print(self.id, ':', 'Inline Query:', query_id, from_id, query_string)

            articles = [{'type': 'article',
                             'id': 'abc', 'title': 'ABC', 'message_text': 'Good morning'}]

            self.bot.answerInlineQuery(query_id, articles)
            print(self.id, ':', 'Answers sent.')

        elif flavor == 'chosen_inline_result':
            result_id, from_id, query_string = telepot.glance2(msg, flavor=flavor)
            print(self.id, ':', 'Chosen Inline Result:', result_id, from_id, query_string)
示例#19
0
    def handle(self, msg):
        flavor = telepot.flavor(msg)

        if flavor == "normal":  # normal message
            content_type, chat_type, chat_id = telepot.glance2(msg)
            if content_type == 'text':
                if TelegramBot.is_command(msg):  # bot command
                    cmd, params = TelegramBot.parse_command(msg['text'])
                    user_id = TelegramBot.get_user_id(msg)
                    args = {
                        'params': params,
                        'user_id': user_id,
                        'chat_type': chat_type
                    }
                    if cmd in self.commands:
                        yield from self.commands[cmd](self, chat_id, args)
                    else:
                        yield from self.sendMessage(
                            chat_id, "Unknown command: {cmd}".format(cmd=cmd))

                else:  # plain text message
                    yield from self.onMessageCallback(self, chat_id, msg)

            elif content_type == 'location':
                yield from self.onLocationShareCallback(self, chat_id, msg)

            elif content_type == 'new_chat_participant':
                yield from self.onUserJoinCallback(self, chat_id, msg)

            elif content_type == 'left_chat_participant':
                yield from self.onUserLeaveCallback(self, chat_id, msg)

            elif content_type == 'photo':
                yield from self.onPhotoCallback(self, chat_id, msg)

        elif flavor == "inline_query":  # inline query e.g. "@gif cute panda"
            query_id, from_id, query_string = telepot.glance2(msg,
                                                              flavor=flavor)
            print("inline_query")

        elif flavor == "chosen_inline_result":
            result_id, from_id, query_string = telepot.glance2(msg,
                                                               flavor=flavor)
            print("chosen_inline_result")

        else:
            raise telepot.BadFlavor(msg)
示例#20
0
 def handle(self, msg):
     content_type, chat_type, chat_id = telepot.glance2(msg)
     # Do your stuff according to `content_type` ...
     # print(chat_id)
     if chat_id in adminchatid:  # Store adminchatid variable in tokens.py
         if content_type == 'text':
             if msg['text'] == '/stats' and chat_id not in shellexecution:
                 bot.sendChatAction(chat_id, 'typing')
                 memory = psutil.virtual_memory()
                 disk = psutil.disk_usage('/')
                 boottime = datetime.fromtimestamp(psutil.boot_time())
                 now = datetime.now()
                 timedif = "Online for: %.1f Hours" % (((now - boottime).total_seconds()) / 3600)
                 memtotal = "Total memory: %.2f GB " % (memory.total / 1000000000)
                 memavail = "Available memory: %.2f GB" % (memory.available / 1000000000)
                 memuseperc = "Used memory: " + str(memory.percent) + " %"
                 diskused = "Disk used: " + str(disk.percent) + " %"
                 pids = psutil.pids()
                 pidsreply = ''
                 procs = {}
                 for pid in pids:
                     p = psutil.Process(pid)
                     try:
                         pmem = p.memory_percent()
                         if pmem > 0.5:
                             if p.name() in procs:
                                 procs[p.name()] += pmem
                             else:
                                 procs[p.name()] = pmem
                     except:
                         None
                 sortedprocs = sorted(procs.items(), key=operator.itemgetter(1), reverse=True)
                 for proc in sortedprocs:
                     pidsreply += proc[0] + " " + ("%.2f" % proc[1]) + " %\n"
                 reply = timedif + "\n" + \
                         memtotal + "\n" + \
                         memavail + "\n" + \
                         memuseperc + "\n" + \
                         diskused + "\n\n" + \
                         pidsreply
                 bot.sendMessage(chat_id, reply, disable_web_page_preview=True)
             elif msg['text'] == "Stop":
                 clearall(chat_id)
                 bot.sendMessage(chat_id, "All operations stopped.", reply_markup=hide_keyboard)
             elif msg['text'] == "/shell" and chat_id not in shellexecution:
                 bot.sendMessage(chat_id, "Send me a shell command to execute", reply_markup=stopmarkup)
                 shellexecution.append(chat_id)
             elif chat_id in shellexecution:
                 bot.sendChatAction(chat_id, 'typing')
                 p = Popen(msg['text'], shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
                 output = p.stdout.read()
                 if output != b'':
                     bot.sendMessage(chat_id, output, disable_web_page_preview=True)
                 else:
                     bot.sendMessage(chat_id, "No output.", disable_web_page_preview=True)
             elif msg['text'] == '/memgraph':
                 bot.sendChatAction(chat_id, 'typing')
                 tmperiod = "Last %.2f hours" % ((datetime.now() - graphstart).total_seconds() / 3600)
                 bot.sendPhoto(chat_id, plotmemgraph(memlist, xaxis, tmperiod))
示例#21
0
async def assert_text(msg, chat_handler):
    content_type, chat_type, chat_id = telepot.glance2(msg)
    if content_type != 'text':
        await chat_handler.sender.sendMessage(
            _s["msg_expecttext"]
        )
        return False
    return True
示例#22
0
def handle(msg):
    flavor = telepot.flavor(msg)
    # normal message
    if flavor == 'normal':
        content_type, chat_type, chat_id = telepot.glance2(msg)
        print('Normal Message:', content_type, chat_type, chat_id)
        command = msg['text']
        if command == '/start':
            start(chat_id)
        elif command == '/help':
            help(chat_id)
        elif command == '/settings':
            settings(chat_id)
        else:
            unknown(chat_id)

        return ('Message sent')

        # Do your stuff according to `content_type` ...

    # inline query - need `/setinline`
    elif flavor == 'inline_query':
        query_id, from_id, query_string = telepot.glance2(msg, flavor=flavor)
        print('Inline Query:', query_id, from_id, query_string)

        # Compose your own answers
        articles = [{
            'type': 'article',
            'id': 'abc',
            'title': 'ABC',
            'message_text': 'Good morning'
        }]

        bot.answerInlineQuery(query_id, articles)

    # chosen inline result - need `/setinlinefeedback`
    elif flavor == 'chosen_inline_result':
        result_id, from_id, query_string = telepot.glance2(msg, flavor=flavor)
        print('Chosen Inline Result:', result_id, from_id, query_string)

        # Remember the chosen answer to do better next time

    else:
        raise telepot.BadFlavor(msg)
示例#23
0
    def on_message(self, msg):
        self._count += 1
        flavor = telepot.flavor(msg)

        print "%s %d: %d: %s: %s" % (
            type(self).__name__,
            self.id,
            self._count,
            flavor,
            telepot.glance2(msg, flavor=flavor),
        )
示例#24
0
    def handle_message(self, msg, chat_handler):
        content_type, chat_type, chat_id = telepot.glance2(msg)
        tasks = []
        success = 0
        failure = 0
        muted = 0


        for group_membership in GroupMembership.select().where(GroupMembership.group == self._group):
            try:
                if not Mute.select().where(Mute.group == self._group, Mute.user==group_membership.user, Mute.until > datetime.datetime.now()):
                    telegram_id = group_membership.user.telegram_id
                    main_character_name = chat_handler.user.main_character.name
                    group_name = self._group.group_name

                    if content_type == "text":
                        tasks.append(self.safe_send(telegram_id, main_character_name, group_name, msg))

                    elif content_type == "photo":
                        tasks.append(self.bot.sendMessage(telegram_id,"Ping from:" + main_character_name + " to " + group_name))
                        tasks.append(self.bot.sendPhoto(telegram_id, msg["photo"][1]["file_id"], caption=msg["caption"]))

                    elif content_type == "document":
                        tasks.append(self.bot.sendMessage(telegram_id,"Ping from:" + main_character_name + " to " + group_name))
                        tasks.append(self.bot.sendDocument(telegram_id, msg["document"]["file_id"]))

                    elif content_type == "voice":
                        tasks.append(self.bot.sendMessage(telegram_id,"Ping from:" + main_character_name + " to " + group_name))
                        tasks.append(self.bot.sendVoice(telegram_id, msg["voice"]["file_id"]))

                    elif content_type == "video":
                        tasks.append(self.bot.sendMessage(telegram_id,"Ping from:" + main_character_name + " to " + group_name))
                        tasks.append(self.bot.sendVideo(telegram_id, msg["video"]["file_id"]))

                    elif content_type == "sticker":
                        tasks.append(self.bot.sendMessage(telegram_id,"Ping from:" + main_character_name + " to " + group_name))
                        tasks.append(self.bot.sendSticker(telegram_id, msg["sticker"]["file_id"]))
                    success += 1
                else:
                    muted += 1
            except:
                failure += 1

        self.finished()

        start_time = time.time()
        yield from chat_handler.throttle(tasks)
        elapsed = time.time() - start_time

        rounded = math.floor(elapsed*100)/100

        yield from chat_handler.sender.sendMessage(
            "Ping sent to "+str(success)+" users in "+str(rounded)+" seconds"
        )
示例#25
0
文件: app.py 项目: vasua/verycruelbot
    def on_message(self, msg):
        content_type, chat_type, chat_id = telepot.glance2(msg)
        m = telepot.namedtuple(msg, 'Message')

        if chat_id < 0:
            # public chat
            if not self.reply_to_kek(content_type, m):
                self.reply_to_badgay(content_type, m)
        else:
            # private conversation
            self.reply_to_badgay(content_type, m)
示例#26
0
def handle(msg):
	
	content_type, chat_type, chat_id = telepot.glance2(msg)
	if content_type is 'photo':
		pprint(msg['photo'])
		for i,f in enumerate(msg['photo']):
			print(f['file_id'])

			bot.downloadFile(f['file_id'],'C:/Users/Diane/newpicture.jpeg')
			with open('C:/Users/Diane/newpicture.jpeg','rb') as fichierPhoto:
				bot.sendPhoto(chat_id,fichierPhoto)
	bot.sendMessage(chat_id,'merci')
示例#27
0
def handle_message(msg):
    try:
        username = msg['from']['username']
    except:
        username = ''
    content_type, chat_type, chat_id = telepot.glance2(msg)
    if chat_type == 'group' and username in admins:
        if content_type is 'text':
            command = msg['text'].lower()
            actions(command)
    else:
        bot.sendMessage(group_id, 'Desculpe '+username+' nao tenho permissao para falar com voce!')
示例#28
0
    def on_message(self, msg):
        content_type, chat_type, chat_id = telepot.glance2(msg)

        if not chat_id in VALID_USERS:
            print("Permission Denied %s" % chat_id)
            return

        if content_type is 'text':
            print("recieving : ", msg['text'])
            #self.handle_command(unicode(msg['text']))
            self.handle_command(str(msg['text']), chat_id)
            return
示例#29
0
def answer(msg):
    flavor = telepot.flavor(msg)

    if flavor == 'inline_query':
        query_id, from_id, query = telepot.glance2(msg, flavor=flavor)

        if from_id != USER_ID:
            print('Unauthorized user:'******'InlineQuery')

        articles = [InlineQueryResultArticle(
                       id='abc', title='HK', message_text='Hong Kong', url='https://www.google.com', hide_url=True),
                   {'type': 'article',
                       'id': 'def', 'title': 'SZ', 'message_text': 'Shenzhen', 'url': 'https://www.yahoo.com'}]

        photos = [InlineQueryResultPhoto(
                      id='123', photo_url='https://core.telegram.org/file/811140934/1/tbDSLHSaijc/fdcc7b6d5fb3354adf', thumb_url='https://core.telegram.org/file/811140934/1/tbDSLHSaijc/fdcc7b6d5fb3354adf'),
                  {'type': 'photo',
                      'id': '345', 'photo_url': 'https://core.telegram.org/file/811140184/1/5YJxx-rostA/ad3f74094485fb97bd', 'thumb_url': 'https://core.telegram.org/file/811140184/1/5YJxx-rostA/ad3f74094485fb97bd', 'caption': 'Caption', 'title': 'Title', 'message_text': 'Message Text'}]

        results = random.choice([articles, photos])

        yield from bot.answerInlineQuery(query_id, results, cache_time=20, is_personal=True, next_offset='5')

    elif flavor == 'chosen_inline_result':
        result_id, from_id, query = telepot.glance2(msg, flavor=flavor)

        if from_id != USER_ID:
            print('Unauthorized user:'******'ChosenInlineResult')

        print('Chosen inline query:')
        pprint.pprint(msg)

    else:
        raise telepot.BadFlavor(msg)
示例#30
0
    def handle(self, msg):
        flavor = telepot.flavor(msg)

        if flavor == "normal":  # normal message
            content_type, chat_type, chat_id = telepot.glance2(msg)
            if content_type == 'text':
                if TelegramBot.is_command(msg):  # bot command
                    cmd, params = TelegramBot.parse_command(msg['text'])
                    user_id = TelegramBot.get_user_id(msg)
                    args = {'params': params, 'user_id': user_id, 'chat_type': chat_type}
                    if cmd in self.commands:
                        yield from self.commands[cmd](self, chat_id, args)
                    else:
                        yield from self.sendMessage(chat_id, "Unknown command: {cmd}".format(cmd=cmd))

                else:  # plain text message
                    yield from self.onMessageCallback(self, chat_id, msg)

            elif content_type == 'location':
                yield from self.onLocationShareCallback(self, chat_id, msg)

            elif content_type == 'new_chat_participant':
                yield from self.onUserJoinCallback(self, chat_id, msg)

            elif content_type == 'left_chat_participant':
                yield from self.onUserLeaveCallback(self, chat_id, msg)

            elif content_type == 'photo':
                yield from self.onPhotoCallback(self, chat_id, msg)

        elif flavor == "inline_query":  # inline query e.g. "@gif cute panda"
            query_id, from_id, query_string = telepot.glance2(msg, flavor=flavor)
            print("inline_query")

        elif flavor == "chosen_inline_result":
            result_id, from_id, query_string = telepot.glance2(msg, flavor=flavor)
            print("chosen_inline_result")

        else:
            raise telepot.BadFlavor(msg)
示例#31
0
def handle(msg):
    content_type, chat_type, chat_id = telepot.glance2(msg)
    text = msg["text"]

    last_chat = chat_id
    print(content_type, chat_type, chat_id)

    if text[0] == "/":
        response = command_response(text.lower()[1:])
    else:
        response = "aloha, I am countdownforbot."

    bot.sendMessage(chat_id, response)
示例#32
0
    def on_message(self, msg):
        content_type, chat_type, chat_id = telepot.glance2(msg)

        if chat_id in self._exclude:
            print('Chat id %d is excluded.' % chat_id)
            return

        if content_type != 'text':
            print('Content type %s is ignored.' % content_type)
            return

        print('Storing message: %s' % msg)
        self._store.put(msg)
    def on_message(self, msg):
        content_type, chat_type, chat_id = telepot.glance2(msg)

        if chat_id in self._exclude:
            print('Chat id %d is excluded.' % chat_id)
            return

        if content_type != 'text':
            print('Content type %s is ignored.' % content_type)
            return

        print('Storing message: %s' % msg)
        self._store.put(msg)
示例#34
0
    def on_message(self, msg):
        flavor = telepot.flavor(msg)
        self._counts[flavor] += 1

        print(self.id, ':', self._counts)

        # Have to answer inline query to receive chosen result
        if flavor == 'inline_query':
            query_id, from_id, query_string = telepot.glance2(msg, flavor=flavor)

            articles = [{'type': 'article',
                             'id': 'abc', 'title': 'ABC', 'message_text': 'Good morning'}]

            self.bot.answerInlineQuery(query_id, articles)
示例#35
0
def handle_message(msg):
    try:
        username = msg['from']['username']
    except:
        username = ''
    content_type, chat_type, chat_id = telepot.glance2(msg)
    if chat_type == 'group' and username in admins:
        if content_type is 'text':
            command = msg['text'].lower()
            actions(command)
    else:
        bot.sendMessage(
            group_id, 'Desculpe ' + username +
            ' nao tenho permissao para falar com voce!')
示例#36
0
def handle(msg):
    pprint.pprint(msg)

    msg_type, chat_type, chat_id = telepot.glance2(msg)

    if msg.get("text", "").startswith("/"):
        welcome = (
            "Hello!\n"
            "Any message, picture, sound, video sent to me will be displayed "
            "live on {wall_url}\n"
            "This project is open source!\n"
            "Check out https://github.com/leplatrem/kinto-telegram-wall#readme"
        ).format(wall_url=WALL_URL)
        bot.sendMessage(chat_id, welcome)
        return

    # Attributes sent to Kinto.
    record = {
        "date": msg["date"],
        "from": {
            "first_name": msg["from"]["first_name"]
        }
    }
    content = msg[msg_type]

    tmpfile = None
    try:
        if msg_type not in DOWNLOAD_TYPES:
            record[msg_type] = content
            kinto_create_record(record)
        else:
            if msg_type == "photo":
                content = content[-1]

            filesize = content.get("file_size")
            if filesize > DOWNLOAD_MAX_SIZE:
                bot.sendMessage(chat_id, "File is too big!")
                return

            tmpfile, filename, mimetype = download_from_telegram(content)
            print((tmpfile, filename, mimetype))
            kinto_create_attachment(record, tmpfile, filename, mimetype)
        bot.sendMessage(chat_id, THUMB_UP)
    except Exception as e:
        print(e)
        bot.sendMessage(chat_id,
                        "An error occured. Contact %s" % CONTACT_SUPPORT)
    finally:
        if tmpfile and os.path.exists(tmpfile):
            os.remove(tmpfile)
def handle_message(msg):
    user_id = str(msg['from']['id'])
    username = str(msg['from']['username'])
    nome = str(msg['from']['first_name'])
    try:
        sobrenome = str(msg['from']['last_name'])
    except:
        sobrenome = ""
    content_type, chat_type, chat_id = telepot.glance2(msg)

    if username in admins:
        if content_type is 'photo':
            file_id = msg['photo'][len(msg['photo'])-1]['file_id']
            bot.downloadFile(file_id, 'photos/'+file_id+'.jpg')

    else:
        bot.sendMessage(user_id, 'Desculpe '+nome+' '+sobrenome+' nao tenho permissao para falar com voce!')
    def on_message(self, msg):
        print(u'on_message() is being called')
        flavor = telepot.flavor(msg)

        # normal message
        if chkNConv(flavor) == u'normal':
            content_type, chat_type, _chat_id = telepot.glance2(msg)
            print('Normal Message:', content_type, chat_type, _chat_id, '; message content: ', msg)

            if content_type == 'text':
                if self._convert_type == ConverType.nothing:
                    if chkNConv(msg['text']) == u'/start':
                        self.sender.sendMessage(text=bot_starting_script)
                    elif chkNConv(msg['text']) == u'/newgame' or chkNConv(msg['text']) == u'/newgame@' + chkNConv(bot_name):
                        self.create_game(msg=msg)
        else:
            raise telepot.BadFlavor(msg)
示例#39
0
    def on_message(self, msg):
        content_type, chat_type, chat_id = telepot.glance2(msg)

        if content_type != 'text':
            self.sender.sendMessage(
                'Give me valid note denominations only, please.')
            return

        if msg['text'].strip() == 'Cancel':
            self.sender.sendMessage('Game cancelled.',
                                    reply_markup=self._start_keyboard)
            self.close()
            return

        if msg['text'].strip() == 'Done':
            sum = 0
            for i in self._fsm.split():
                x = int(i)
                sum += x

            # check the guess against the answer ...
            if sum != self._answer:
                # give a descriptive hint
                hint = self._hint(self._answer, sum)
                self.sender.sendMessage(hint)
            else:
                self.sender.sendMessage('Correct!',
                                        reply_markup=self._start_keyboard)
                self.close()

        try:
            m = msg['text'].strip().split()
            if m[0] != 'Done':
                x = int(m[0])
                if x not in [10, 20, 50, 100, 500, 1000]:
                    raise ValueError
                #self.sender.sendMessage('Game cancelled.', reply_markup=self._start_keyboard  )
                self._fsm = self._fsm + ' ' + msg['text'].strip()
                self.sender.sendMessage('Target: Rs. %s   Notes added: %s' %
                                        (self._answer, self.formatfsm()))
                return

        except:
            self.sender.sendMessage('Give me valid note denominations, please')
            return
示例#40
0
def examine(result, type):
    try:
        print 'Examining %s ......' % type

        nt = telepot.namedtuple.namedtuple(result, type)
        assert equivalent(result, nt), 'Not equivalent:::::::::::::::\n%s\n::::::::::::::::\n%s' % (result, nt)

        if type == 'Message':
            print 'Message glance2: %s' % str(telepot.glance2(result, long=True))

        pprint.pprint(result)
        pprint.pprint(nt)
        print
    except AssertionError:
        traceback.print_exc()
        answer = raw_input('Do you want to continue? [y] ')
        if answer != 'y':
            exit(1)
示例#41
0
    def handle(self, msg):
        content_type, chat_type, user_id = telepot.glance2(msg)

        if user_id in MASTER_ID:
            if content_type == "text":
                text = msg["text"]
                if '/shell:' in text:
                    cmd = text[7:]
                    proc = os.popen(cmd)
                    self.sendMessage(user_id, proc.read())
                elif '/download:' in text:
                    path = text[10:]
                    doc = open(path, 'rb')
                    self.sendDocument(user_id, doc)
            elif content_type == "document":
                file_id = msg["document"]["file_id"]
                file_name = msg["document"]["file_name"]
                self.downloadFile(file_id, file_name)
示例#42
0
def handle(msg):
    content_type, chat_type, chat_id = telepot.glance2(msg)

    print(msg)

    if content_type is 'sticker':
        with open('stockSticker', 'rb') as fichier:
            pickler = pickle.Unpickler(fichier)
            f = pickler.load()  #renvoie le 1er objet lu
        f += [msg['sticker']['file_id']
              ]  #rajoute l'id du sticker envoyé au 1er objet
        sticky = choice(f)
        with open('stockSticker', 'wb') as fichier:
            pickler = pickle.Pickler(fichier)
            pickler.dump(
                f)  #écrit le dernier sticker envoyé à la fin du fichier

        bot.sendSticker(chat_id, sticky)
def handle_message(msg):
    user_id = str(msg['from']['id'])
    username = str(msg['from']['username'])
    nome = str(msg['from']['first_name'])
    try:
        sobrenome = str(msg['from']['last_name'])
    except:
        sobrenome = ""
    content_type, chat_type, chat_id = telepot.glance2(msg)

    if username in admins:
        if content_type is 'photo':
            file_id = msg['photo'][len(msg['photo']) - 1]['file_id']
            bot.downloadFile(file_id, 'photos/' + file_id + '.jpg')

    else:
        bot.sendMessage(
            user_id, 'Desculpe ' + nome + ' ' + sobrenome +
            ' nao tenho permissao para falar com voce!')
示例#44
0
def handle_message(msg):
    try:
        username = msg['from']['username']
    except:
        username = ''
    content_type, chat_type, chat_id = telepot.glance2(msg)
    support_commands = ['/ticket','/graph','/servers']
    admin_commands = ['/ticket','/graph','/servers','/balance']
    if chat_type == 'group':
        if content_type is 'text':
            command = msg['text'].lower().split()
            if username in admins and command[0] in admin_commands:
                actions(command,username)
            elif username in support and command[0] in support_commands:
                actions(command,username)
            else:
                bot.sendMessage(chat_id, 'Desculpe, voce nao tem permissao pra usar esse comando ou o comando nao existe!')
    else:
        bot.sendMessage(chat_id, 'Desculpe, nao tenho permissao para falar com voce!')
示例#45
0
def see_every_content_types(msg):
    global expected_content_type, content_type_iterator

    content_type, chat_type, chat_id = telepot.glance2(msg)
    from_id = msg['from']['id']

    if chat_id != USER_ID and from_id != USER_ID:
        print('Unauthorized user:'******'Message')
    try:
        if content_type == expected_content_type:
            expected_content_type = next(content_type_iterator)
            yield from bot.sendMessage(chat_id, 'Please give me a %s.' % expected_content_type)
        else:
            yield from bot.sendMessage(chat_id, 'It is not a %s. Please give me a %s, please.' % (expected_content_type, expected_content_type))
    except StopIteration:
        # reply to sender because I am kicked from group already
        yield from bot.sendMessage(from_id, 'Thank you. I am done.')
示例#46
0
    def on_message(self, msg):
        content_type, chat_type, chat_id = telepot.glance2(msg)

        if content_type != 'text':
            self.sender.sendMessage('Give me a number, please.')
            return

        try:
            guess = int(msg['text'])
        except ValueError:
            self.sender.sendMessage('Give me a number, please.')
            return

        # check the guess against the answer ...
        if guess != self._answer:
            # give a descriptive hint
            hint = self._hint(self._answer, guess)
            self.sender.sendMessage(hint)
        else:
            self.sender.sendMessage('Correct!')
            self.close()
示例#47
0
def handle(msg):
    wikipedia.set_lang("fr")
    content_type, chat_type, chat_id = telepot.glance2(msg)
    print(content_type, chat_type, chat_id)
    if content_type == 'sticker':
        bot.sendMessage(chat_id, 'Pardon ?')
    if content_type == 'text':
        command = msg['text'].split()
        print(command)
        if command[0] == '/help':
            bot.sendMessage(chat_id, 'Taper /get suivi du mot recherché')

        if command[0] == '/get':
            if len(command) == 1:
                bot.sendMessage(
                    chat_id,
                    'Quel est le mot recherché ? Taper /get suivi du mot recherché'
                )
            else:
                try:
                    command = command[1:]
                    print(command)
                    command = ' '.join(command[0:])
                    print(command)
                    page = wikipedia.page(command)
                    bot.sendChatAction(chat_id, 'typing')
                    bot.sendMessage(chat_id,
                                    wikipedia.summary(command, sentences=1))
                    bot.sendChatAction(chat_id, 'typing')
                    bot.sendMessage(chat_id, page.url)
                except wikipedia.exceptions.PageError:
                    bot.sendMessage(
                        chat_id,
                        'Il n\'y a aucun résultat correspondant à la requête.')
                except wikipedia.exceptions.DisambiguationError as e:
                    bot.sendMessage(
                        chat_id,
                        'Cette requête renvoie plusieurs résultats, est ce que vous vouliez dire  :'
                    )
                    bot.sendMessage(chat_id, e.options)
示例#48
0
    def on_message(self, msg):
        content_type, chat_type, chat_id = telepot.glance2(msg)
        # Check ID
        if not chat_id in VALID_USERS:
            print("Permission Denied")
            return

        if content_type is 'text':
            self.handle_command(unicode(msg['text']))
            return

        if content_type is 'document':
            file_name = msg['document']['file_name']
            if file_name[-3:] == 'smi':
                file_id = msg['document']['file_id']
                self.handle_smi(file_id, file_name)
                return
            self.sender.sendMessage('인식할 수 없는 파일입니다.')
            return

        print("E")
        self.sender.sendMessage('인식하지 못했습니다')
    def on_message(self, msg):
        content_type, chat_type, chat_id = telepot.glance2(msg)
        
        if content_type != 'text':
            self.sender.sendMessage("I don't understand")
            return

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

        # Tells who has sent you how many messages
        if command == '/unread':
            results = self._store.unread_per_chat()

            lines = []
            for r in results:
                n = 'ID: %d\n%d unread' % r
                lines.append(n)

            if not len(lines):
                self.sender.sendMessage('No unread messages')
            else:
                self.sender.sendMessage('\n'.join(lines))

        # read next sender's messages
        elif command == '/next':
            results = self._store.unread_per_chat()

            if not len(results):
                self.sender.sendMessage('No unread messages')
                return

            chat_id = results[0][0]
            unread_messages = self._store.pull(chat_id)

            self.sender.sendMessage('From ID: %d' % chat_id)
            self._read_messages(unread_messages)

        else:
            self.sender.sendMessage("I don't understand")
    def create_game(self, msg):
        print(u'new game now')
        content_type, chat_type, _chat_id = telepot.glance2(msg)
        game_id = genNewRoomNumber()
        while game_id in all_games:
            game_id = genNewRoomNumber()
        print(u'new game with game id: ' + chkNConv(game_id.__str__()))
        if chat_type == 'group' or chat_type == 'supergroup':
            all_games[game_id] = LiarsDiceGame(game_id=game_id,
                                           host_id=msg['from']['id'],
                                           group_id=msg['chat']['id'])
            group_index[msg['chat']['id']] = game_id
        else:
            all_games[game_id] = LiarsDiceGame(game_id=game_id,
                                           host_id=msg['from']['id'],
                                           group_id=0)

        all_games[game_id].player_list.append(Player(msg['from']['id'], msg['from']['first_name']))
        start_url = telegram_base_url + bot_name + '?start=' + game_id.__str__()
        self.sender.sendMessage(text=bot_invite_player % (chkNConv(msg['from']['first_name']),
                                                          chkNConv(bot_name),
                                                          chkNConv(start_url)))
示例#51
0
    def handle(self, msg):
        content_type, chat_type, chat_id = telepot.glance2(msg)

        if content_type != 'text':
            self.sender.sendMessage(self.msgErro)
            return

        text = msg['text'].strip().lower()
        command = text.split(' ')[0]

        if command == '/regras':
            self.sendMessage(chat_id, self.regras)

        elif command == '/ida':
            try:
                _, pessoa, horario = text.split(' ')
            except ValueError:
                self.sendMessage(
                    chat_id, self.msgErro + " Formato: /ida <nome> <horario>")

            carona = Carona(pessoa, horario)
            self.caronas.append(carona)
            self.sendMessage(chat_id, 'Nova carona ' + str(carona))

        elif command == '/lista':
            if len(self.caronas) == 0:
                resp = "Não ha caronas"

            else:
                resp = ""
                for carona in self.caronas:
                    resp += str(carona) + "\n"

            self.sendMessage(chat_id, resp)

        else:
            self.sendMessage(chat_id, self.msgErro)
    def on_message(self, msg):
        content_type, chat_type, chat_id = telepot.glance2(msg)

        # Check ID
        if chat_id not in VALID_USERS:
            logger.warning("Permission Denied (user:{}) (chat:{})".format(
                chat_id, chat_type))
            self.sender.sendMessage(self.ERROR_PERMISSION_DENIED)
            return

        if content_type is 'text':
            cmd = msg['text']
            logger.info(
                "Message received (user:{}) (chat:{}) (type:{}) (text:{})".
                format(chat_id, chat_type, content_type, cmd))
            self.handle_command(cmd)
            return
        else:
            logger.info(
                "Message received (user:{}) (chat:{}) (type:{})".format(
                    chat_id, chat_type, content_type))

        logger.error("Error: Command '{}' not recognized".format(msg))
        self.sender.sendMessage("I don't know what you mean...")
示例#53
0
def handle(msg):
    content_type, chat_type, chat_id = telepot.glance2(msg)
    m = telepot.namedtuple(msg, 'Message')

    if chat_id < 0:
        # group message
        print 'Received a %s from %s, by %s' % (content_type, m.chat, m.from_)
    else:
        # private message
        print 'Received a %s from %s' % (content_type, m.chat
                                         )  # m.chat == m.from_

    if content_type == 'text':
        reply = ''

        # For long messages, only return the first 10 characters.
        if len(msg['text']) > 10:
            reply = u'First 10 characters:\n'

        # Length-checking and substring-extraction may work differently
        # depending on Python versions and platforms. See above.

        reply += msg['text'][:10].encode('unicode-escape').decode('ascii')
        bot.sendMessage(chat_id, reply)
示例#54
0
def handle(msg):
    content_type, chat_type, chat_id = telepot.glance2(msg)
    m = telepot.namedtuple(msg, 'Message')

    if chat_id < 0:
        # group message
        logger.info('Received a %s from %s, by %s' %
                    (content_type, m.chat, m.from_))
    else:
        # private message
        logger.info('Received a %s from %s' %
                    (content_type, m.chat))  # m.chat == m.from_

    if content_type == 'text':
        if msg['text'] == '/start':
            yield from bot.sendMessage(
                chat_id,  # Welcome message
                "You send me an Emoji"
                "\nI give you the Unicode"
                "\n\nOn Python 2, remember to prepend a 'u' to unicode strings,"
                "e.g. \U0001f604 is u'\\U0001f604'")
            return

        reply = ''

        # For long messages, only return the first 10 characters.
        if len(msg['text']) > 10:
            reply = 'First 10 characters:\n'

        # Length-checking and substring-extraction may work differently
        # depending on Python versions and platforms. See above.

        reply += msg['text'][:10].encode('unicode-escape').decode('ascii')

        logger.info('>>> %s', reply)
        yield from bot.sendMessage(chat_id, reply)
示例#55
0
def send_everything(msg):
    content_type, chat_type, chat_id, msg_date, msg_id = telepot.glance2(
        msg, long=True)

    if chat_id != USER_ID:
        print('Unauthorized user:'******'Received message from ID: %d' % chat_id)
    print('Start sending various messages ...')

    ##### forwardMessage

    r = yield from bot.forwardMessage(chat_id, chat_id, msg_id)
    examine(r, 'Message')

    ##### sendMessage

    r = yield from bot.sendMessage(
        chat_id,
        'Hello, I am going to send you a lot of things.',
        reply_to_message_id=msg_id)
    examine(r, 'Message')

    r = yield from bot.sendMessage(chat_id, '中文')
    examine(r, 'Message')

    r = yield from bot.sendMessage(
        chat_id,
        '*bold text*\n_italic text_\n[link](http://www.google.com)',
        parse_mode='Markdown')
    examine(r, 'Message')

    yield from bot.sendMessage(chat_id,
                               'http://www.yahoo.com\nwith web page preview')

    yield from bot.sendMessage(chat_id,
                               'http://www.yahoo.com\nno web page preview',
                               disable_web_page_preview=True)

    show_keyboard = {'keyboard': [['Yes', 'No'], ['Maybe', 'Maybe not']]}
    hide_keyboard = {'hide_keyboard': True}
    force_reply = {'force_reply': True}

    nt_show_keyboard = telepot.namedtuple.ReplyKeyboardMarkup(**show_keyboard)
    nt_hide_keyboard = telepot.namedtuple.ReplyKeyboardHide(**hide_keyboard)
    nt_force_reply = telepot.namedtuple.ForceReply(**force_reply)

    yield from bot.sendMessage(chat_id,
                               'Here is a custom keyboard',
                               reply_markup=show_keyboard)

    yield from asyncio.sleep(2)

    yield from bot.sendMessage(chat_id,
                               'Hiding it now.',
                               reply_markup=nt_hide_keyboard)

    yield from bot.sendMessage(chat_id,
                               'Force reply',
                               reply_markup=nt_force_reply)

    ##### sendPhoto

    yield from bot.sendChatAction(chat_id, 'upload_photo')
    r = yield from bot.sendPhoto(chat_id, open('lighthouse.jpg', 'rb'))
    examine(r, 'Message')

    file_id = r['photo'][0]['file_id']

    yield from bot.sendPhoto(chat_id,
                             file_id,
                             caption='Show original message and keyboard',
                             reply_to_message_id=msg_id,
                             reply_markup=nt_show_keyboard)

    yield from bot.sendPhoto(chat_id,
                             file_id,
                             caption='Hide keyboard',
                             reply_markup=hide_keyboard)

    r = yield from aiohttp.get('http://i.imgur.com/B1fzGoh.jpg')
    bbb = yield from r.read()

    yield from bot.sendPhoto(chat_id, ('abc.jpg', bbb))

    ##### getFile

    f = yield from bot.getFile(file_id)
    examine(f, 'File')

    ##### downloadFile

    try:
        print('Downloading file to non-existent directory ...')
        yield from bot.downloadFile(file_id, 'non-existent-dir/file')
    except:
        print('Error: as expected')

    print('Downloading file to down.1 ...')
    yield from bot.downloadFile(file_id, 'down.1')

    print('Open down.2 and download to it ...')
    with open('down.2', 'wb') as down:
        yield from bot.downloadFile(file_id, down)

    ##### sendAudio
    # Need one of `performer` or `title' for server to regard it as audio. Otherwise, server treats it as voice.

    yield from bot.sendChatAction(chat_id, 'upload_audio')
    r = yield from bot.sendAudio(chat_id,
                                 open('dgdg.mp3', 'rb'),
                                 title='Ringtone')
    examine(r, 'Message')

    file_id = r['audio']['file_id']

    yield from bot.sendAudio(chat_id,
                             file_id,
                             duration=6,
                             performer='Ding Dong',
                             title='Ringtone',
                             reply_to_message_id=msg_id,
                             reply_markup=show_keyboard)

    yield from bot.sendAudio(chat_id,
                             file_id,
                             performer='Ding Dong',
                             reply_markup=nt_hide_keyboard)

    ##### sendDocument

    yield from bot.sendChatAction(chat_id, 'upload_document')
    r = yield from bot.sendDocument(chat_id, open('document.txt', 'rb'))
    examine(r, 'Message')

    file_id = r['document']['file_id']

    yield from bot.sendDocument(chat_id,
                                file_id,
                                reply_to_message_id=msg_id,
                                reply_markup=nt_show_keyboard)

    yield from bot.sendDocument(chat_id, file_id, reply_markup=hide_keyboard)

    ##### sendSticker

    r = yield from bot.sendSticker(chat_id, open('gandhi.png', 'rb'))
    examine(r, 'Message')

    file_id = r['sticker']['file_id']

    yield from bot.sendSticker(chat_id,
                               file_id,
                               reply_to_message_id=msg_id,
                               reply_markup=show_keyboard)

    yield from bot.sendSticker(chat_id, file_id, reply_markup=nt_hide_keyboard)

    ##### sendVideo

    yield from bot.sendChatAction(chat_id, 'upload_video')
    r = yield from bot.sendVideo(chat_id, open('hktraffic.mp4', 'rb'))
    examine(r, 'Message')

    try:
        file_id = r['video']['file_id']

        yield from bot.sendVideo(chat_id,
                                 file_id,
                                 duration=5,
                                 caption='Hong Kong traffic',
                                 reply_to_message_id=msg_id,
                                 reply_markup=nt_show_keyboard)
        yield from bot.sendVideo(chat_id, file_id, reply_markup=hide_keyboard)

    except KeyError:
        # For some reason, Telegram servers may return a document.
        print('****** sendVideo returns a DOCUMENT !!!!!')

        file_id = r['document']['file_id']

        yield from bot.sendDocument(chat_id,
                                    file_id,
                                    reply_to_message_id=msg_id,
                                    reply_markup=nt_show_keyboard)
        yield from bot.sendDocument(chat_id,
                                    file_id,
                                    reply_markup=hide_keyboard)

    ##### downloadFile, multiple chunks

    print('Downloading file to down.3 ...')
    yield from bot.downloadFile(file_id, 'down.3')

    ##### sendVoice

    r = yield from bot.sendVoice(chat_id, open('example.ogg', 'rb'))
    examine(r, 'Message')

    file_id = r['voice']['file_id']

    yield from bot.sendVoice(chat_id,
                             file_id,
                             duration=6,
                             reply_to_message_id=msg_id,
                             reply_markup=show_keyboard)

    yield from bot.sendVoice(chat_id, file_id, reply_markup=nt_hide_keyboard)

    ##### sendLocation

    yield from bot.sendChatAction(chat_id, 'find_location')
    r = yield from bot.sendLocation(chat_id, 22.33, 114.18)  # Hong Kong
    examine(r, 'Message')

    yield from bot.sendLocation(chat_id,
                                49.25,
                                -123.1,
                                reply_to_message_id=msg_id,
                                reply_markup=nt_show_keyboard)  # Vancouver

    yield from bot.sendLocation(chat_id,
                                -37.82,
                                144.97,
                                reply_markup=hide_keyboard)  # Melbourne

    ##### Done sending messages

    yield from bot.sendMessage(chat_id, 'I am done.')
示例#56
0
def handle(msg):
    """
    Just do the actions for each command listed in the conditions.
    We have to refactor it puting all commands at a tuple or list, etc.
    The bot username will be dinamically alterable, too.
    """
    global bot_names
    command = ''
    print msg
    content_type, chat_type, chat_id = telepot.glance2(msg)
    print content_type, chat_type, chat_id
    if content_type == 'text':
        command = utf8_encode(msg['text'].lower())

    name = utf8_encode(msg['from']['first_name'])

    print 'Got command: %s' % command

    names_to_check = verify_text(bot_names, command)
    print names_to_check

    if names_to_check or chat_type == 'private':
        command = remove_bot_name(names_to_check, command)
        print command

        if command.lower() in morning_words:
            bot.sendMessage(chat_id, "Good morning, {}!".format(name))
        elif command.lower() in night_words:
            bot.sendMessage(chat_id, "Good night, {}!".format(name))
        elif command == 'que dia é hoje?':
            day = datetime.datetime.now().day
            month = months.get(calendar.month_name[datetime.datetime.now().month], '')
            bot.sendMessage(
                chat_id, "É dia de você calar essa boca. \n\nBrincadeira, hoje é dia {day} de {month} \U0001f605".format(day=day, month=month))
        elif command == 'bem vindo!':
            if welcome_count < 1:
                msg_wel = "Eu sempre estive aqui, idiota! {}".format(Emoji.NEUTRAL_FACE)
            elif welcome_count == 1:
                msg_wel = "Não repito. {}".format(Emoji.NEUTRAL_FACE)
            else:
                msg_wel = "{}".format(Emoji.NEUTRAL_FACE)
            bot.sendMessage(chat_id, msg_wel)
            globals()['welcome_count'] += 1
            print globals()['welcome_count']
        elif command.lower() in love_words:
            msgs = [
                "Eu tambem amo vc, {}! {}{}".format(name,
                                                    Emoji.BLACK_HEART_SUIT,
                                                    Emoji.BLACK_HEART_SUIT),
                "Legal.",
            ]
            msg = random.choice(msgs)
            bot.sendMessage(chat_id, msg)
            if msg == "Legal.":
                bot.sendChatAction(chat_id, 'upload_document')
                bot.sendDocument(chat_id, "BQADBAADdwMAAgMdZAdPtWmOPGN1IQI")
        elif command.lower() == 'que horas são?':
            msg = "É muita hipocrisia da sua parte me perguntar isso {}... "\
                  "Você pode vizualisar facilmente as horas olhando para parte "\
                  "inferior direita do seu comentário."
            bot.sendMessage(chat_id, msg.format(name))
            bot.sendChatAction(chat_id, 'upload_document')
            bot.sendDocument(chat_id, "BQADAQADEwADnqxzCGp0fqkzsPC6Ag")
        elif command.lower() == 'nós te amamos!':
            msg = "Ah é?! Foda-se."
            bot.sendMessage(chat_id, msg)
            bot.sendChatAction(chat_id, 'upload_document')
            bot.sendDocument(chat_id, "BQADBAADYwMAAiUcZAe1DjlP-IMGhQI")
        elif command.lower() == 'é bininu binina ou binunu binino?'.lower():
            msg = "bininu."
            bot.sendMessage(chat_id, msg)
        elif command.lower() == 'qual sua idade?':
            msg = "Você sabe a idade de Deus, seu criador? Pois é, sou 1 ano mais novo que Ele."
            bot.sendMessage(chat_id, msg)
        elif command.lower() == '/emojis':
            msg1, msg2, msg3, msg4, msg5 = get_all_emojis()
            bot.sendMessage(chat_id, msg1)
            bot.sendMessage(chat_id, msg2)
            bot.sendMessage(chat_id, msg3)
            bot.sendMessage(chat_id, msg4)
            bot.sendMessage(chat_id, msg5)
        elif command.lower() in fuck_words:
            msg = [
                "Querido, por favor! Tenha boas maneiras! Você tem que me convidar pra jantar primeiro.",
                "Entre na fila.",
                "Sonhando novamente, querido?",
                "Se sentindo sozinho de novo, ha?",
                "É só eu ou você diz isso para todos?",
                "Sério? Agora?",
                "Não obrigado. Eu passo.",
            ]
            bot.sendMessage(chat_id, random.choice(msg))
            # bot.sendChatAction(chat_id, 'upload_document')
            # bot.sendDocument(chat_id, "BQADBAADdwMAAgMdZAdPtWmOPGN1IQI")
        elif verify_text(command.lower().split(), 'trans'):
            msg = command.lower().replace('trans ', '')
            if msg.split()[0] == 'pt':
                msg = msg.replace("pt ", "", 1)
                print msg
                os.system('echo "{}" | trans -b -o ~/output.txt :pt'.format(msg))
            else:
                os.system('echo "{}" | trans -b -o ~/output.txt :en'.format(msg))
            with open(os.environ['HOME'] + '/output.txt', 'r') as content_file:
                content = content_file.read()
            bot.sendMessage(chat_id, content)
        elif equals_text(quote_words, command):
            msg = get_quotes(db, bot, chat_id)
            bot.sendMessage(chat_id, re.sub(' +', ' ', msg.replace('.', ',')))
        # jokes
        elif equals_text(joke_words, command):
            jokes = my_shuffle(Joke(db).get_jokes())
            bot.sendMessage(chat_id, random.choice(jokes))
        elif verify_text(lyrics_words, command):
            lyrics, status = get_lyrics(command)
            bot.sendMessage(chat_id, lyrics, parse_mode='Markdown')
        elif verify_text(extractor_words, command):
            url = command.split()[1]
            msg = v2.extract(url)
            try:
                bot.sendMessage(chat_id, msg)
            except BadHTTPResponse:
                msg = ("*Infelizmente o texto é muito grande e excedeu nosso limite."
                       " Por favor tente extrair textos um pouco menores.*")
                bot.sendMessage(chat_id, msg, parse_mode='Markdown')
        else:
            cnt_ed = count_ed_mgs(db)
            cnt_simsimi = count_simsimi_msg(db)
            on_the_music_group_id = -82861655
            los_primos_group_id = -16994629
            shit_group = -78912892
            fucked_list_group = [los_primos_group_id, on_the_music_group_id, shit_group]
            limit_ed = 5 if chat_id == sminino_group_id else 1 if chat_id in fuck_list_group else 3
            limit_simsimi = 2 if chat_id == sminino_group_id else 8 if chat_id in fuck_list_group else 3
            print 'limit_ed', limit_ed
            print 'limit_simsimi', limit_simsimi
            if cnt_ed < limit_ed:
                response, sim_status, robot_name = get_ed_reply(command)
            elif cnt_simsimi < limit_simsimi:
                response, sim_status, robot_name = get_simsimi_reply(command)
            else:
                response, ed_status, robot_name = get_ed_reply(command)
                if ed_status != 200:
                    response, sim_status, robot_name = get_simsimi_reply(command)
                q = {'qty_answed_message': 0}
                db.set('ed_info', q)
                db.set('simsimi_info', q)
                db.dump()

            if verify_text(['Fui criado e program', 'O meu inventor'], response):
                developed_by_texts = db.get('developed_by')
                olds = [utf8_encode(text) for text in developed_by_texts['old']]
                news = [utf8_encode(text) for text in developed_by_texts['new']]
                if 'Fui criado e program' in response:
                    response = response.replace(
                            olds[0],
                            news[0])
                    response += ' {}'.format(Emoji.GRINNING_FACE)
                if 'O meu inventor' in response:
                    response = response.replace(
                            olds[1],
                            news[1])
            info_sent = bot.sendMessage(chat_id, response)
            if info_sent:
                print robot_name
                try:
                    count_msg = db.get('{}_info'.format(robot_name))['qty_answed_message']
                    count_msg += 1
                except:
                    count_msg = 0
                q = {'qty_answed_message': count_msg}
                db.set('{}_info'.format(robot_name), q)
                db.dump()
    elif verify_text(command.lower().split(), 'kkk'*15):
            msgs = [
                'hahaha',
                'kkkk',
            ]
            bot.sendMessage(chat_id, random.choice(msgs))