def main(bot, *args, **kwargs): """ picachoo Return picture from picachoo.ru Usage: /picachoo [pic number] [page number] """ user_page = None user_index = None try: user_page = int(args[1]) user_index = int(args[0]) except: pass matricies = json.loads(bot.store.get('picachoo_matricies') or '[]') curr_index = int(bot.store.get('picachoo_index') or 0) curr_page = int(bot.store.get('picachoo_page') or 0) if not user_page is None: curr_page = user_page if curr_index >= len(matricies) or not user_page is None: response = requests.get( 'https://www.picachoo.ru/more/{}'.format(curr_page + 1), verify=False) matricies = list( set(re.findall("/files/thumb/.*?.jpg", response.content.decode('utf-8')))) matricies = list( map(lambda x: 'https://picachoo.ru{}'.format(x.replace('/thumb', '')), matricies)) bot.store.set('picachoo_matricies', json.dumps(matricies)) curr_page += 1 curr_index = 0 if not user_page is None and not user_index is None: curr_index = user_index % len(matricies) try: matrix = matricies[curr_index] except IndexError: return 'Page not found' ext = matrix.split('.')[2] chat_id = kwargs.pop('chat_id') bot.pre_send(chat_id=chat_id, action='upload_photo') if user_page is None and user_index is None: bot.store.set('picachoo_index', curr_index + 1) bot.store.set('picachoo_page', curr_page) bot.call( 'sendPhoto', 'POST', data={'chat_id': chat_id}, files={'photo': ( 'file.{}'.format(ext), prepare_binary_from_url(matrix, verify=False), 'image/' + ext )} )
def main(bot, *args, **kwargs): """ /tweet Post replayed message to twitter """ twitter_options = getattr(bot.settings, 'twitter_keys', None) if not twitter_options: return 'Module is not configured. You must set `twitter_keys` in settings' api = getattr(bot, 'twitter_api', None) if api is None: api = bot.twitter_api = twitter.Api( consumer_key=twitter_options['consumer_key'], consumer_secret=twitter_options['consumer_secret'], access_token_key=twitter_options['access_token_key'], access_token_secret=twitter_options['access_token_secret']) message = kwargs['update']['message'] reply = message.get('reply_to_message', None) media = None if reply is None: text = ' '.join(args) elif reply.get('photo'): file = reply.get('photo')[-1] file_id = file['file_id'] data = {'file_id': file_id} file_info = bot.call('getFile', 'GET', data=data) file_path = file_info.get('file_path') file_url = "https://api.telegram.org/file/bot{}/{}".format( bot.settings.token, file_path) media = prepare_binary_from_url(file_url) # Hacking for compatibility setattr(media, 'mode', 'rb') setattr(media, 'name', 'tmp_file.jpg') text = message_author(reply) if reply.get('text'): text = '{}: {}'.format(text, reply['text']) elif reply.get('text'): name = message_author(reply) text = "{}: {}".format(name, reply['text']) else: return try: tweet = api.PostUpdate(text, media) screen_name = tweet.user.screen_name result = "https://twitter.com/{}/status/{}".format( screen_name, tweet.id_str) except twitter.error.TwitterError as e: result = "Some problem with your tweet: {}".format(e.message) except Exception as e: result = "Polomkah: {}".format(e) return result
def main(bot, *args, **kwargs): """ kot Stupid cat memes from http://kotomatrix.ru """ matricies = json.loads(bot.store.get('kot_matricies').decode() or '[]') curr_index = int(bot.store.get('kot_index') or 0) if curr_index >= len(matricies): response = requests.get('http://kotomatrix.ru/rand/') matricies = list(set(re.findall( "http://kotomatrix.ru/images/.*.jpg", response.content.decode('utf-8') ))) bot.store.set('kot_matricies', json.dumps(matricies)) curr_index = 0 matrix = matricies[curr_index] ext = matrix.split('.')[2] chat_id = kwargs.pop('chat_id') bot.pre_send(chat_id=chat_id, action='upload_photo') bot.call( 'sendPhoto', 'POST', data = {'chat_id': chat_id}, files = {'photo': ( 'file.{}'.format(ext), prepare_binary_from_url(matrix), 'image/' + ext )} ) bot.store.set('kot_index', curr_index + 1)
def main(bot, *args, **kwargs): """ img [query] Search for images around the internet. If no query specified, return next image from previous query. See also: g """ global response chat_id = kwargs.pop('chat_id') query = ' '.join(args) last_query = getattr(bot, 'img_last_query_{}'.format(chat_id), None) i = 0 last_time = getattr(bot, 'img_last_time_{}'.format(chat_id), None) if last_time and last_time > datetime.now() - timedelta(seconds=1): return 'Not so fast' if last_query == query or (not args and last_query): if not args: query = last_query i = getattr(bot, 'img_last_num_{}'.format(chat_id)) + 1 elif not args: return response(bot, 'Invalid syntax, read `/man img`', chat_id) setattr(bot, 'img_last_query_{}'.format(chat_id), query) key = getattr(bot.settings, 'azure_bing_api_key', None) if not key: return response(bot, 'Azure Bing API Key is not specified in settings', chat_id) auth = base64.b64encode(bytes('{0}:{0}'.format(key), 'utf-8')) headers = {'Authorization': 'Basic {}'.format(auth.decode('utf-8'))} # Cache return response to decrease number of requests to the bing api if last_query != query: # TODO: use `params` here, investigate 'Query is not of type String' error from azure try: azure_response = requests.get( 'https://api.datamarket.azure.com/Bing/Search/v1/Image?Market=%27ru-RU%27&Adult=%27Moderate%27&Query=%27{}%27&$format=json&$top=20' .format(query), headers=headers, timeout=(1, 2)).content except requests.exceptions.Timeout: return response(bot, 'Can not get results', chat_id) except RequestException: return response(bot, 'Can not get results') setattr(bot, 'img_last_response_{}'.format(chat_id), azure_response) else: azure_response = getattr(bot, 'img_last_response_{}'.format(chat_id)) try: search_data = json.loads(azure_response.decode('utf-8')) except ValueError: return response(bot, 'Can not get results', chat_id) results = search_data.get('d', {}).get('results', []) if len(results) >= i + 1: while results[i - 1 if i > 1 else i:]: setattr(bot, 'img_last_num_{}'.format(chat_id), i) if len(results) <= i: return response(bot, 'No such images', chat_id) url = results[i]['MediaUrl'] ext = url.rsplit('.', 1)[1] if ext.lower() in ('jpg', 'jpeg', 'gif', 'png'): file_id = check_store(bot, url) photo = file_id if file_id else prepare_binary_from_url(url) if photo: break i += 1 else: return response(bot, 'No such images', chat_id) data = {'chat_id': chat_id} if file_id: data.update(photo=file_id) files = None else: files = { 'photo': ('file.{}'.format(ext), photo, results[i]['ContentType']) } # Send custom chat action bot.pre_send(chat_id=chat_id, action='upload_photo') telegram_response = bot.call('sendPhoto', 'POST', data=data, files=files) setattr(bot, 'img_last_time_{}'.format(chat_id), datetime.now()) if telegram_response and telegram_response.get( 'photo') and not file_id and bot.store: bot.store.set(url, telegram_response['photo'][-1]['file_id']) elif not telegram_response or telegram_response.get( 'status_code') == 400: return "Telegram can't process the image" else: return response(bot, 'No such images', chat_id)