def on_chat_message(msg):
pprint(msg)
content_type, chat_type, chat_id = telepot.glance(msg)
# Ignore any messages received over 30s ago
cur_time = time.time()
if cur_time - msg.get("date") < 30:
if content_type == 'text':
text = msg.get("text")
for url in URLS:
if url in text:
# This means the message contains a link to some music, let's save it
get_fuego(msg)
save_link(msg)
break
else:
print("IGNORING OLD MESSAGE...")
python类glance()的实例源码
def handle(msg):
global look_obj
content_type, chat_type, chat_id = telepot.glance(msg)
print(content_type, chat_type, chat_id)
#if content_type == 'text':
#bot.sendMessage(chat_id, msg['text'])
msg_txt=msg['text']
words=msg_txt.split(' ')
#print(words[-1])
ai = apiai.ApiAI(CLIENT_ACCESS_TOKEN)
request = ai.text_request()
request.query = msg_txt
response = request.getresponse()
reply = response.read()
reply = reply.decode("utf-8")
parsed_json = json.loads(reply)
action = parsed_json['result']['action']
parameters = parsed_json['result']['parameters']
response = parsed_json['result']['fulfillment']['speech']
#return parameters, action, response
print(action)
print(parameters['object'])
if action=='go_to':
look_obj=str(parameters['object'])
print(look_obj)
bot.sendMessage(chat_id, ("I'll look for a " + str(parameters['object']) + "!") )
#TOKEN = sys.argv[1] # get token from command-line
def __init__(self, msg, bot):
self.bot = bot
if msg.get('data'):
self.query_id, self.from_id, self.query_data = telepot.glance(
msg, flavor='callback_query')
self.chat_id = msg['message']['chat']['id']
self.chat_type = msg['message']['chat']['type']
self.UserID = msg['from']['id']
self.msg = msg
else:
self.content_type, self.chat_type, self.chat_id = telepot.glance(
msg)
self.msg_id = msg['message_id']
if 'username' in msg['from']:
self.username = msg['from']['username']
else:
self.username = '[Sem username]'
self.user = msg['from']['first_name']
self.UserID = msg['from']['id']
self.msg = msg
def __handle_message(self, message):
"""
Handles a message sent from telegram.
:param message:
:return:
"""
try:
content_type, chat_type, chat_id = telepot.glance(message)
telegram_message = TelegramResponse(content_type, chat_type, chat_id, message)
# TODO: Do an enum for the content types
if content_type == 'text':
print telegram_message.message.text
user_id = telegram_message.message.message_from.id
response = process_message(self.twitter_api, telegram_message)
if response:
self.bot.sendMessage(user_id, response)
except Exception as ex:
ExceptionHandler.handle_exception(ex, False)
def on_chat_message(self, msg):
content_type, chat_type, chat_id = telepot.glance(msg)
if '/start' not in msg['text']:
search = msg['text']
search.replace(" ", "+")
self._results = spotify.search(q=search, type='track', limit='50')
pages = math.ceil(len(self._results['tracks']['items']) / 3)
inlinekeyboards = []
if pages == 1:
for track in self._results['tracks']['items']:
trackname = track['artists'][0]['name'] + ' -' + ' ' + track['name']
inlinekeyboards.append([InlineKeyboardButton(text=trackname, callback_data=track['uri'])])
keyboard = InlineKeyboardMarkup(inline_keyboard=inlinekeyboards)
self.print_search(keyboard, msg)
elif pages > 1:
for track in self._results['tracks']['items'][:3]:
trackname = track['artists'][0]['name'] + ' -' + ' ' + track['name']
inlinekeyboards.append([InlineKeyboardButton(text=trackname, callback_data=track['uri'])])
current = 1
pagekeyboard = self.get_pagination(current, pages)
inlinekeyboards.append(pagekeyboard)
keyboard = InlineKeyboardMarkup(inline_keyboard=inlinekeyboards)
self.print_search(keyboard, msg)
def handle(msg):
"""
This function handle all messages incoming from users
"""
content_type, chat_type, chat_id = telepot.glance(msg)
command_input = msg['text']
if command_input == '/start':
# Check if already registred
if register_user(chat_id):
bot.sendMessage(chat_id, start_msg)
feed = feedparser.parse(feed_url)
# Send all news from older to newest
for entry in reversed(feed.entries):
msg = entry.title + '\n' + entry.link
bot.sendMessage(chat_id, msg)
if command_input == '/stop':
bot.sendMessage(chat_id, stop_msg)
remove_user(chat_id)
def on_chat_message(self, msg):
'''process and response message'''
ntuple = Message(**msg)
if telepot.glance(msg)[0] == 'text':
if any(q in ntuple.text for q in ACTION_DICT.keys()):
response = perform_action(ntuple.text, ntuple.from_.id)
else:
response = KERNEL.respond(ntuple.text)
#if not response:
#response = self.sender.sendMessage(
# chat_id, 'I do not understand your last message.', reply_to_message_id=msg_id)
self.sender.sendMessage(response)
def on_message(self, msg):
debug('MainDialog on_message')
content_type = telepot.glance(msg)[0]
if content_type != 'text':
return
text = msg['text']
if text == self._GAMES_DB:
return DIALOG_BROWSING, {}
elif text == self._RECENTLY_PLAYED:
return DIALOG_LAST_PLAYED, {}
elif text == self._HOWTO:
await self._sender.sendMessage(HELP_MESSAGE, parse_mode='Markdown')
else:
await self._sender.sendMessage('Choose section', reply_markup=self._KEYBOARD)
return DIALOG_MAIN, {}
def on_message(self, msg):
debug('BrowsingDialog on_message %s', msg)
content_type = telepot.glance(msg)[0]
if content_type != 'text':
return DIALOG_BROWSING, {}
text = msg['text']
if text == self._FORWARD:
items = self._iterator.next()
elif text == self._BACKWARD:
items = self._iterator.prev()
elif text == self._CANCEL:
return DIALOG_MAIN, {}
elif text.startswith('/'):
return DIALOG_GAME, {'game': text[1:]}
else:
items = self._iterator.get_page()
msg = self._make_items_list(items)
await self._sender.sendMessage(msg, reply_markup=self._make_keyboard())
return DIALOG_BROWSING, {}
def on_message(self, msg):
debug('GameDialog on_message')
content_type = telepot.glance(msg)[0]
if content_type != 'text':
return
text = msg['text']
if text.startswith('/command'):
text = text[9:]
elif text.startswith('/c'):
text = text[3:]
if text.lower() in ['save', 'restore', 'quit', 'q']:
await self._sender.sendMessage('This command currently unsupported',
reply_markup=self._KEYBOARD)
return DIALOG_GAME, {}
elif text == self._RETURN:
return DIALOG_MAIN, {}
elif not text:
return DIALOG_GAME, {}
else:
await self._game.command(text)
return DIALOG_GAME, {}
def handle_message(msg):
user_id = msg['from']['id']
nome = msg['from']['first_name']
try:
sobrenome = msg['from']['last_name']
except:
sobrenome = ''
username = msg['from']['username']
hostname = subprocess.check_output(['hostname']).lower()
content_type, chat_type, chat_id = telepot.glance(msg)
if username in admins:
if content_type is 'document':
bot.downloadFile(msg['document']['file_id'], msg['document']['file_name'])
elif content_type is 'text':
command = msg['text'].lower()
actions(user_id,command,hostname)
else:
bot.sendMessage(user_id, 'Desculpe '+nome+' '+sobrenome+' nao tenho permissao para falar com voce!')
def on_chat_message(self, message):
try:
content_type, chat_type, chat_id = telepot.glance(message)
if content_type in self.UNRECOGNIZED_CONTENT_TYPES:
raise BotException("Message content not understood.")
message_text = message["text"]
if self._is_command(message_text):
result = self._process_command_text(message["text"])
else:
result = self._process_query_text(message["text"])
await self._send_reply(message, result)
except Exception as e:
try:
exception_string = str(e)
except:
exception_string = "Unprintable exception."
finally:
error_message = "ERROR: " + exception_string
await self._send_reply(message,
self._format_as_html(error_message))
def on_inline_query(self, message):
query_id, from_id, query_string = telepot.glance(message,
flavor="inline_query")
def _compute_answer():
result = self._process_query_text(query_string)
return [
{
"type": "article",
"id": self._generate_random_id(),
"title": "0xDEADBEEF",
"input_message_content": {
"message_text": result,
"parse_mode": "HTML"
}
}
]
self._answerer.answer(message, _compute_answer)
def __init__(self, message_json):
try:
content_type, chat_type, chat_id = telepot.glance(message_json)
except KeyError:
raise UnsupportedContentError()
if 'forward_from' in message_json:
raise UnsupportedContentError()
self.is_reply = 'reply_to_message' in message_json
self.text = message_json.get('text')
self.type = content_type
self.command = None
self.command_args = None
try:
init_method = getattr(self, '_init_' + content_type)
except AttributeError:
raise UnsupportedContentError()
init_method(message_json)
def on_inline_query(self, query):
query_id, from_id, query_string = telepot.glance(query, flavor='inline_query')
LOGGER.debug('Inline query from %d: \"%s\"', self._stranger.id, query_string)
response = [{
'type': 'article',
'id': 'invitation_link',
'title': _('Rand Talk Invitation Link'),
'description': _('The more friends\'ll use your link -- the faster the search will be'),
'thumb_url': 'http://randtalk.ml/static/img/logo-500x500.png',
'message_text': (
_('Do you want to talk with somebody, practice in foreign languages or you just want '
'to have some fun? Rand Talk will help you! It\'s a bot matching you with '
'a random stranger of desired sex speaking on your language. {0}'),
self._stranger.get_invitation_link(),
),
'parse_mode': 'Markdown',
}]
await self._sender.answer_inline_query(query_id, response)
def on_chat_message(self, msg):
content_type, chat_type, chat_id = telepot.glance(msg)
# Check ID
if not chat_id in VALID_USERS:
print("Permission Denied")
return
if content_type is 'text':
self.handle_command(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_smifile(file_id, file_name)
return
if file_name[-7:] == 'torrent':
file_id = msg['document']['file_id']
self.handle_seedfile(file_id, file_name)
return
self.sender.sendMessage('Invalid File')
return
self.sender.sendMessage('Invalid File')
def do_leave(self, msg, match):
query_id, _, _ = telepot.glance(msg, flavor='callback_query')
chat_id = msg['message']['chat']['id']
room_name = match.group('room')
client = self._get_client(chat_id)
prev_focus_room = client.get_focus_room_alias()
client.leave_room(room_name)
self.sendMessage(chat_id, 'Left {}'.format(room_name))
curr_focus_room = client.get_focus_room_alias()
if curr_focus_room != prev_focus_room and curr_focus_room is not None:
self.sendMessage(chat_id,
'You are now participating in: {}'.format(
client.get_focus_room_alias()))
self.answerCallbackQuery(query_id, 'Done!')
def on_inline_query(message):
query_id, from_id, query = telepot.glance(message, flavor='inline_query')
global plugins
@asyncio.coroutine
def get_inline():
for plugin in plugins:
if 'inline_query' in plugin:
for pattern in plugin['inline_patterns']:
if re.search(pattern, query, re.IGNORECASE|re.MULTILINE):
matches = re.findall(pattern, query, re.IGNORECASE)
return_values = yield from plugin['inline_query'](message, matches[0], from_id, 0)
if return_values:
return {'results': return_values, 'cache_time': 0}
break
return []
try:
answerer.answer(message, get_inline)
except:
pass
def inline(message, matches, chat_id, step):
query_id, from_id, query = telepot.glance(message, flavor='inline_query')
response = requests.get(query)
soup = BeautifulSoup(response.text, "html.parser")
image = soup.find("meta", {"property": "og:image"})
video = soup.find("meta", {"property": "og:video"})
if video:
width = soup.find("meta", {"property": "og:video:width"})
height = soup.find("meta", {"property": "og:video:height"})
return [InlineQueryResultVideo(
id=str(uuid.uuid4()), description='Instagram Video', title="Instagram Video", mime_type="video/mp4",
thumb_url=image['content'], video_url=video['content'], video_width=int(width['content']),
video_height=int(height['content']))]
elif image:
return [InlineQueryResultPhoto(
id=str(uuid.uuid4()), title="Instagram Photo",
photo_url=image['content'], photo_width=300, photo_height=300,
thumb_url=image['content'])]
else:
return [InlineQueryResultArticle(
id=str(uuid.uuid4()), title='Error', description="Not Found",
input_message_content=InputTextMessageContent(message_text="Error\nNot Found", parse_mode="Markdown"),
thumb_url="http://siyanew.com/bots/custom.jpg")]
def on_chat_message(self, msg):
"""Answer only chat messages."""
if msg['text'] == "/start":
return
chat_id = telepot.glance(msg)[2]
for engine in (self.katcr, self.thepiratebay):
res = tuple(engine.search(msg['text'], 1))
if res:
break
keyboard = InlineKeyboardMarkup(inline_keyboard=list(
[InlineKeyboardButton(text=k, callback_data=str(r))]
for r, (k, _, _) in enumerate(res)))
self.responses[chat_id] = {r: (k, v) for r, (k, _, v)
in enumerate(res)}
self.sendMessage(chat_id, "Results for: {}".format(msg['text']),
reply_markup=keyboard, parse_mode="html")
def on_callback_query(self, msg):
global alerting_on, snapshooter, snapshot_queue
query_id, from_id, query_data = telepot.glance(msg, flavor='callback_query')
if verbose:
print('Callback Query:', query_id, from_id, query_data)
if cameras.get(query_data):
bot.answerCallbackQuery(query_id,
text='Schnappschuss von deiner Kamera "{}"'.format(query_data))
snapshot_queue.put({'cameras': [cameras[query_data]],
'chat_id': from_id,
'callback': lambda: self.send_snapshot_menu()})
elif query_data == 'disable':
alerting_on = False
self.bot.answerCallbackQuery(query_id, text='Alarme wurden ausgeschaltet.')
self.send_main_menu()
elif query_data == 'enable':
alerting_on = True
self.bot.answerCallbackQuery(query_id, text='Alarme wurden eingeschaltet.')
self.send_main_menu()
elif query_data == 'snapshot':
self.bot.answerCallbackQuery(query_id)
self.send_snapshot_menu()
def on_callback_query(self, msg):
query_id, self.request_chat_id, query_data = telepot.glance(msg, flavor='callback_query')
self.mongo.chat_id = self.request_chat_id
self.store_contacts(msg)
self.known_user = self.is_user_known()
self.__debug_print('>')
self.__debug_print('> callback')
self.__debug_print(msg)
to_send_msg, keyboard = self.process_command(query_data)
if to_send_msg is None:
await self._editor.editMessageReplyMarkup(reply_markup=keyboard)
self.waiting_for_menu_action = True
else:
await self._cancel_last()
sent = await self.sender.sendMessage(to_send_msg, reply_markup=keyboard, parse_mode='Markdown')
self._editor = telepot.aio.helper.Editor(self.bot, sent)
self._edit_msg_ident = telepot.message_identifier(sent)
self.waiting_for_menu_action = False
def on_chat_message(self, msg):
try:
#print("In on_chat_message")
content_type, chat_type, chat_id = telepot.glance(msg)
print('Chat:', content_type, chat_type, chat_id)
pprint(msg)
requests.insert({"request": msg, "time": datetime.now().isoformat()})
answer = process_command(self.state, msg["text"], msg)
self.sender.sendMessage(parse_mode="HTML", **answer)
except Exception as e:
traceback.print_exc()
print("Error: " + str(e))
self.sender.sendMessage("Error: " + str(e))
def on_callback_query(self, msg):
try:
#print("In on_callback_query")
query_id, from_id, data = telepot.glance(msg, flavor='callback_query')
print('Callback query:', query_id, from_id, data)
pprint(msg)
requests.insert({"request": msg, "time": datetime.now().isoformat()})
answer = process_command(self.state, msg["data"], msg)
self.sender.sendMessage(parse_mode="HTML", **answer)
except Exception as e:
traceback.print_exc()
print("Error: " + str(e))
self.sender.sendMessage("Error: " + str(e))
def on_inline_query(self, msg):
query_id, from_id, query_string = telepot.glance(msg, flavor='inline_query')
#print(self.id, ':', 'Inline Query:', query_id, from_id, query_string)
def compute_answer():
ir = InlineReference()
result = ir.search_inline(query_string)
#print("Inline result: ", result)
return result
self._answerer.answer(msg, compute_answer)
def on_chosen_inline_result(self, msg):
result_id, from_id, query_string = telepot.glance(msg, flavor='chosen_inline_result')
#print(self.id, ':', 'Chosen Inline Result:', result_id, from_id, query_string)
def on_callback_query(self, msg):
query_id, from_id, query_data = glance(msg, flavor='callback_query')
try:
data = self.deserialize(query_data)
except ThatsNotMineException:
return
await self.bot.editMessageText(
telepot.origin_identifier(msg),
text="Selected option: {}".format(data),
reply_markup=self.keyboard)
def on_callback(msg):
""" Reaction to an interaction with an InLineKeyboard """
query_id, from_id, query_data = telepot.glance(msg, flavor='callback_query')
logging.info('Got Callback Query:' + str(query_id) + ' Command:' + query_data + ' From ChatID:' + str(from_id))
# SWITCH/CASE to identify the call and respond consequently
if query_data == '/rectify':
options = [i.split('% ')[1] for i in
msg['message']['text'].split('\n')[msg['message']['text'].split('\n').index('DETAILS: ') + 1:]]
options_buttons = [[InlineKeyboardButton(text=i, callback_data='/rectify_' + i)] for i in options]
options_buttons.append([InlineKeyboardButton(text='<< Go back', callback_data='/back')])
keyboard = InlineKeyboardMarkup(
inline_keyboard=options_buttons)
bot.editMessageReplyMarkup((from_id, msg['message']['message_id']), reply_markup=keyboard)
elif '/rectify_' in query_data:
rectified_classification = query_data[len('/rectify_'):]
new = msg['message']['text'].split('\n')
new[2] = 'UPDATED: ' + rectified_classification
new_message = ''.join('%s\n' % i for i in new)
sample_name = new[1][6:] + '.wav'
db_save_access(os.path.join(data['db_path'], 'smartSlamDB.sqlite'),
os.path.join(data['db_path'], 'Samples', sample_name),
rectified_classification)
keyboard = InlineKeyboardMarkup(
inline_keyboard=[[InlineKeyboardButton(text='Rectify classification?', callback_data='/rectify')]]
)
bot.editMessageText((from_id, msg['message']['message_id']), new_message, reply_markup=keyboard)
elif query_data == '/back':
keyboard = InlineKeyboardMarkup(
inline_keyboard=[[InlineKeyboardButton(text='Rectify classification?', callback_data='/rectify')]]
)
bot.editMessageReplyMarkup((from_id, msg['message']['message_id']), reply_markup=keyboard)
bot_scraping_youtube_views.py 文件源码
项目:telegramBots
作者: medialab-prado
项目源码
文件源码
阅读 20
收藏 0
点赞 0
评论 0
def handle(msg):
content_type, chat_type, chat_id = telepot.glance(msg)
print(content_type, chat_type, chat_id)
if content_type == 'text':
#bot.sendMessage(chat_id, msg)
bot.sendMessage(6579175, numero_view)
if content_type == 'new_chat_member':
bot.sendMessage(chat_id, "wellcome to this awesome group!")
if content_type == 'left_chat_member':
bot.sendMessage(chat_id, "Sayonara baby")
def on_voice_msg(msg):
query_id, from_id, query_data = telepot.glance(msg, flavor='callback_query')
print('Callback Query:', query_id, from_id, query_data)
bot.answerCallbackQuery(query_id, text='Calling....')