desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Sends a request using JSON protocol.'
def _SendJSONRequest(self, user, pwd, otp_entry, exp_code, exp_has_cookie):
request_dict = {'username': user, 'password': pwd, 'otp': otp_entry} headers = {'Content-Type': 'application/json', 'X-Xsrftoken': 'fake_xsrf', 'Cookie': '_xsrf=fake_xsrf'} url = self._tester.GetUrl('/admin/otp') self._tester.http_client.fetch(url, callback=partial(self._VerifyAdminAuthResponse, exp_cod...
'Sends a request using HTTP protocol.'
def _SendHTTPRequest(self, user, pwd, otp_entry, exp_code, exp_has_cookie):
post_body = ('username=%s&password=%s&otp=%s' % (user, pwd, otp_entry)) headers = {'Content-Type': 'application/x-www-form-urlencoded', 'X-Xsrftoken': 'fake_xsrf', 'Cookie': '_xsrf=fake_xsrf'} url = self._tester.GetUrl('/admin/otp') self._tester.http_client.fetch(url, callback=partial(self._VerifyAdminA...
'Deconstructs the admin otp cookie and verifies that test-user and timestamp are correct (timestamp within an epsilon of current time). Calls self.stop() on completion.'
def _VerifyAdminAuthResponse(self, exp_code, exp_has_admin_otp_cookie, response):
try: self.assertEqual(response.code, exp_code) set_cookie = response.headers.get('Set-Cookie', '') match = re.compile('admin_otp="(.*)"').match(set_cookie) if exp_has_admin_otp_cookie: self.assertTrue(match, 'Expecting admin_otp cookie, but none found.') ...
'Test successful register of web user.'
def testRegisterWebUser(self):
self._tester.RegisterFacebookUser(self._facebook_user_dict) self.assertRaisesHttpError(403, self._tester.RegisterFacebookUser, self._facebook_user_dict, self._mobile_device_dict)
'Test successful register of mobile user.'
def testRegisterMobileUser(self):
self._tester.RegisterFacebookUser(self._facebook_user_dict, self._mobile_device_dict) self.assertRaisesHttpError(403, self._tester.RegisterFacebookUser, self._facebook_user_dict)
'Test successful login of web user.'
def testLoginWebUser(self):
(user, device_id) = self._tester.RegisterFacebookUser(self._facebook_user_dict) (user2, device_id2) = self._tester.LoginFacebookUser(self._facebook_user_dict) self.assertEqual(user.user_id, user2.user_id) self.assertEqual(device_id, device_id2) self._tester.LoginFacebookUser(self._facebook_user_dict...
'Test successful login of mobile user.'
def testLoginMobileUser(self):
(user, device_id) = self._tester.RegisterFacebookUser(self._facebook_user_dict) (user2, device_id2) = self._tester.LoginFacebookUser(self._facebook_user_dict, self._mobile_device_dict) self.assertEqual(user.user_id, user2.user_id) self.assertNotEqual(device_id, device_id2) self._tester.LoginFacebook...
'Test successful link of web user.'
def testLinkWebUser(self):
(user, device_id) = self._tester.RegisterFacebookUser(self._facebook_user_dict, self._mobile_device_dict) cookie = self._GetSecureUserCookie(user, device_id) (user2, device_id2) = self._tester.LinkFacebookUser(self._facebook_user2_dict, user_cookie=cookie) self.assertEqual(user.user_id, user2.user_id) ...
'Test successful link of mobile user.'
def testLinkMobileUser(self):
(user, device_id) = self._tester.RegisterFacebookUser(self._facebook_user_dict) cookie = self._GetSecureUserCookie(user, device_id) self._tester.LinkFacebookUser(self._facebook_user2_dict, self._mobile_device_dict, user_cookie=cookie) self._tester.LinkFacebookUser(self._facebook_user2_dict, user_cookie=...
'ERROR: Try to login with Facebook identity that is not linked to a Viewfinder account.'
def testLoginNoExist(self):
self.assertRaisesHttpError(403, self._tester.LoginFacebookUser, self._facebook_user_dict) self.assertRaisesHttpError(403, self._tester.LoginFacebookUser, self._facebook_user_dict, self._mobile_device_dict)
'ERROR: Fail Facebook authentication (which returns None user_dict).'
def testAuthenticationFailed(self):
with mock.patch('tornado.httpclient.AsyncHTTPClient', MockAsyncHTTPClient()) as mock_client: mock_client.map('https://graph.facebook.com/me\\?', (lambda request: httpclient.HTTPResponse(request, 400))) url = self.get_url('/register/facebook?access_token=access_token') self.assertRaisesHttpEr...
'ERROR: Test error on missing facebook access token.'
def testMissingAccessToken(self):
self.assertRaisesHttpError(400, auth_test._SendAuthRequest, self._tester, self.get_url('/register/facebook'), 'POST', request_dict=auth_test._CreateRegisterRequest(self._mobile_device_dict))
'Test end-end Facebook registration scenario using a test Facebook account.'
@async_test_timeout(timeout=30) def testFacebookRegistration(self):
self._validate = False fu = facebook_utils.FacebookUtils() users = fu.QueryFacebookTestUsers(limit=1) assert (len(users) == 1), users def _VerifyAccountStatus(cookie, results): u = results['user'] dev = results['device'] ident = results['identity'] self.assertEqual(id...
'Override get_io_loop() to return IOLoop.instance(). The global IOLoop instance is used by self.http_client.fetch in the testFacebookRegistration test.'
def get_new_ioloop(self):
return ioloop.IOLoop.instance()
'Verify listing of client logs.'
def testListClientLogs(self):
start_timestamp = self._cur_t end_timestamp = start_timestamp response_dict = self._tester.SendAdminRequest('list_client_logs', {'user_id': self._users[0].user_id, 'start_timestamp': start_timestamp, 'end_timestamp': end_timestamp}) urls = self._FilterList(response_dict['log_urls']) self.assertEqual...
'Verify logs can be listed for multiple dates.'
def testMultipleDates(self):
start_timestamp = self._t_minus_2d end_timestamp = self._cur_t response_dict = self._tester.SendAdminRequest('list_client_logs', {'user_id': self._users[0].user_id, 'start_timestamp': start_timestamp, 'end_timestamp': end_timestamp}) urls = self._FilterList(response_dict['log_urls']) self.assertEqua...
'Verify logs can be filtered via regexp.'
def testListFilter(self):
start_timestamp = self._cur_t end_timestamp = self._cur_t response_dict = self._tester.SendAdminRequest('list_client_logs', {'user_id': self._users[0].user_id, 'start_timestamp': start_timestamp, 'end_timestamp': end_timestamp, 'filter': 'cl1.t.2'}) urls = self._FilterList(response_dict['log_urls']) ...
'Verify limit is respected.'
@mock.patch.object(client_log, 'MAX_CLIENT_LOGS', 1) def testLimit(self):
response_dict = self._tester.SendAdminRequest('list_client_logs', {'user_id': self._users[0].user_id, 'start_timestamp': self._cur_t, 'end_timestamp': self._cur_t, 'filter': 'dev-2'}) urls = response_dict['log_urls'] self.assertEqual(2, len(urls)) self.assertTrue(urls[0]['filename'].endswith('dev-2-cl1....
'Fetches the client log specified by "url" and returns the contents to "callback".'
def _FetchClientLog(self, url):
response = self._RunAsync(self._tester.http_client.fetch, url, method='GET') self.assertEqual(200, response.code) return response.body
'Remove op logs from response that were created by base class user registration.'
def _FilterList(self, log_urls):
return [log_url for log_url in log_urls if ('Operation' not in log_url['url'])]
'GET is used when authenticating via the web application. If code isn\'t supplied in URL params, redirects to Google with a request for authentication. Google redirects to this URL again on successful authentication with a code which is then used to authorize user information and contacts.'
@handler.asynchronous(datastore=True) @gen.engine def get(self, action):
self._StartInteractiveRequest(action) if (not self.get_argument('code', False)): url = AuthGoogleHandler._OAUTH2_AUTH_URL args = {'client_id': self.settings['google_client_id'], 'redirect_uri': ('https://%s/%s/google' % (self.request.host, action)), 'response_type': 'code', 'access_type': 'offli...
'POST is used when authenticating via the mobile application. The device info is in the JSON-encoded request body. A device id will be allocated and returned with the response.'
@handler.asynchronous(datastore=True) @gen.engine def post(self, action):
(yield gen.Task(self._StartJSONRequest, action, self.request, json_schema.AUTH_FB_GOOGLE_REQUEST)) device_dict = self._request_message.dict.get('device', None) if self.get_argument('refresh_token', False): refresh_token = self.get_argument('refresh_token') url = AuthGoogleHandler._OAUTH2_ACC...
'Parses the google access token from the JSON response body. Gets user data via OAUTH2 with access token.'
@gen.engine def _GetUserInfo(self, device_dict, refresh_token, response):
tokens = www_util.ParseJSONResponse(response) assert tokens, 'unable to fetch access token' access_token = tokens['access_token'] expires = tokens['expires_in'] if (tokens.has_key('refresh_token') and (not refresh_token)): refresh_token = tokens['refresh_token'] assert access...
'Refreshes the lookup database by iterating over all cities in the geoprocessor and querying google maps for address components for any that are missing.'
def RefreshDB(self, callback):
def _OnLookup(city, barrier_cb, response): if (response.code != 200): logging.error(('error in google maps API query: %s' % response)) else: try: json_response = json.loads(response.body) components = [] if (le...
'Saves the database to disk by writing to a temporary file and then renames.'
def SaveDB(self):
tmp_file = (options.options.lookupdb + '.bak') try: with open(tmp_file, 'w') as wf: json.dump(self._lookup_db, wf) os.rename(tmp_file, options.options.lookupdb) except: logging.exception('unable to write lookup database') os.unlink(tmp_file)
'Returns the list of cities.'
def GetCities(self):
return self._data
'Returns the number of places being processed.'
def NumCities(self):
return len(self._data)
'Filters out a set of places which match the place name entries which lie between (start, end), inclusive. If there are more than --datafile_size places with the prefix, the places are sorted by population. The largest --datafile_size places are bundled into a sorted datafile. In addition, the same prefix range is recu...
def RecursivelyCreateDataFiles(self, start='', end='', cities=None):
if (not cities): cities = self._data if (len(cities) > options.options.datafile_size): pop_sorted = sorted(cities, key=attrgetter('pop'), reverse=True) output = pop_sorted[:options.options.datafile_size] leftover = [] for city in cities: if (len(city.name) == ...
'Applies the boost to US cities, sorts by population and outputs the list of files to output directory.'
def FilterTopCities(self):
filtered_cities = [] for city in self._data: filtered_cities.append(city) cities_sorted = sorted(filtered_cities, key=attrgetter('name'), cmp=locale.strcoll) with codecs.open(os.path.join(options.options.output_dir, 'top_cities.txt'), 'w', 'utf-8') as f: for c in cities_sorted: ...
'Strips illegal characters from place name and returns new name.'
def _CleanName(self, name):
return name.strip((string.whitespace + string.punctuation))
'Loads and parses the provided datafile into an array of placename information.'
def _ParseUSPostal(self, datafile):
self._us_postal = [] with open(datafile, 'r') as f: for line in f.readlines(): fields = line.split(' DCTB ') datum = GeoDatum(None, self._CleanName(fields[2].decode('utf-8')), float(fields[9]), float(fields[10]), fields[0], fields[4], fields[5], None) self._us_postal....
'Loads and parses the provided datafile into an array of placename information.'
def _ParseCities(self, datafile):
count_under = 0 count_over = 0 us_postal_places = [d.name for d in self._us_postal] self._data = [] with open(datafile, 'r') as f: for line in f.readlines(): fields = line.split(' DCTB ') population = int(fields[14]) if (fields[8] == 'US'): ...
'Add few seconds to now so the token get refreshed before it invalidates in the middle of the request'
def check_access_token(self):
now_s = (get_time() + 120) if (self._access_token is not None): if (self._access_token_expiry == 0): self.log.debug('No Access Token Expiry found - assuming it is still valid!') return True elif (self._access_token_expiry > now_s): ...
'Schedule some data to emit at an absolute timestamp. :type when: int or float :type data: dictionary :return: an internal Event object'
def event_at(self, when, data):
return self._insert_event(data, when)
'Schedule some data to emit after a number of seconds. :type delay: int or float :type data: dictionary :return: an internal Event object'
def event_later(self, delay, data):
return self._insert_event(data, (time.time() + delay))
'Emit some data as soon as possible. :type data: dictionary :return: an internal Event object'
def event_now(self, data):
return self._insert_event(data, time.time())
'Cancel an event. :type event: an internal Event object'
def cancel(self, event):
self._remove_event(event)
'See: https://core.telegram.org/bots/api#getme'
def getMe(self):
return self._api_request('getMe')
'See: https://core.telegram.org/bots/api#sendmessage'
def sendMessage(self, chat_id, text, parse_mode=None, disable_web_page_preview=None, disable_notification=None, reply_to_message_id=None, reply_markup=None):
p = _strip(locals()) return self._api_request('sendMessage', _rectify(p))
'See: https://core.telegram.org/bots/api#forwardmessage'
def forwardMessage(self, chat_id, from_chat_id, message_id, disable_notification=None):
p = _strip(locals()) return self._api_request('forwardMessage', _rectify(p))
'See: https://core.telegram.org/bots/api#sendphoto :param photo: a string indicating a ``file_id`` on server or HTTP URL of a photo from the Internet, a file-like object as obtained by ``open()`` or ``urlopen()``, or a (filename, file-like object) tuple. If the file-like object is obtained by ``urlopen()``, you most li...
def sendPhoto(self, chat_id, photo, caption=None, disable_notification=None, reply_to_message_id=None, reply_markup=None):
p = _strip(locals(), more=['photo']) return self._api_request_with_file('sendPhoto', _rectify(p), 'photo', photo)
'See: https://core.telegram.org/bots/api#sendaudio :param audio: Same as ``photo`` in :meth:`telepot.Bot.sendPhoto`'
def sendAudio(self, chat_id, audio, caption=None, duration=None, performer=None, title=None, disable_notification=None, reply_to_message_id=None, reply_markup=None):
p = _strip(locals(), more=['audio']) return self._api_request_with_file('sendAudio', _rectify(p), 'audio', audio)
'See: https://core.telegram.org/bots/api#senddocument :param document: Same as ``photo`` in :meth:`telepot.Bot.sendPhoto`'
def sendDocument(self, chat_id, document, caption=None, disable_notification=None, reply_to_message_id=None, reply_markup=None):
p = _strip(locals(), more=['document']) return self._api_request_with_file('sendDocument', _rectify(p), 'document', document)
'See: https://core.telegram.org/bots/api#sendvideo :param video: Same as ``photo`` in :meth:`telepot.Bot.sendPhoto`'
def sendVideo(self, chat_id, video, duration=None, width=None, height=None, caption=None, disable_notification=None, reply_to_message_id=None, reply_markup=None):
p = _strip(locals(), more=['video']) return self._api_request_with_file('sendVideo', _rectify(p), 'video', video)
'See: https://core.telegram.org/bots/api#sendvoice :param voice: Same as ``photo`` in :meth:`telepot.Bot.sendPhoto`'
def sendVoice(self, chat_id, voice, caption=None, duration=None, disable_notification=None, reply_to_message_id=None, reply_markup=None):
p = _strip(locals(), more=['voice']) return self._api_request_with_file('sendVoice', _rectify(p), 'voice', voice)
'See: https://core.telegram.org/bots/api#sendvideonote :param video_note: Same as ``photo`` in :meth:`telepot.Bot.sendPhoto` :param length: Although marked as optional, this method does not seem to work without it being specified. Supply any integer you want. It seems to have no effect on the video note\'s display size...
def sendVideoNote(self, chat_id, video_note, duration=None, length=None, disable_notification=None, reply_to_message_id=None, reply_markup=None):
p = _strip(locals(), more=['video_note']) return self._api_request_with_file('sendVideoNote', _rectify(p), 'video_note', video_note)
'See: https://core.telegram.org/bots/api#sendlocation'
def sendLocation(self, chat_id, latitude, longitude, disable_notification=None, reply_to_message_id=None, reply_markup=None):
p = _strip(locals()) return self._api_request('sendLocation', _rectify(p))
'See: https://core.telegram.org/bots/api#sendvenue'
def sendVenue(self, chat_id, latitude, longitude, title, address, foursquare_id=None, disable_notification=None, reply_to_message_id=None, reply_markup=None):
p = _strip(locals()) return self._api_request('sendVenue', _rectify(p))
'See: https://core.telegram.org/bots/api#sendcontact'
def sendContact(self, chat_id, phone_number, first_name, last_name=None, disable_notification=None, reply_to_message_id=None, reply_markup=None):
p = _strip(locals()) return self._api_request('sendContact', _rectify(p))
'See: https://core.telegram.org/bots/api#sendgame'
def sendGame(self, chat_id, game_short_name, disable_notification=None, reply_to_message_id=None, reply_markup=None):
p = _strip(locals()) return self._api_request('sendGame', _rectify(p))
'See: https://core.telegram.org/bots/api#sendinvoice'
def sendInvoice(self, chat_id, title, description, payload, provider_token, start_parameter, currency, prices, photo_url=None, photo_size=None, photo_width=None, photo_height=None, need_name=None, need_phone_number=None, need_email=None, need_shipping_address=None, is_flexible=None, disable_notification=None, reply_to_...
p = _strip(locals()) return self._api_request('sendInvoice', _rectify(p))
'See: https://core.telegram.org/bots/api#sendchataction'
def sendChatAction(self, chat_id, action):
p = _strip(locals()) return self._api_request('sendChatAction', _rectify(p))
'See: https://core.telegram.org/bots/api#getuserprofilephotos'
def getUserProfilePhotos(self, user_id, offset=None, limit=None):
p = _strip(locals()) return self._api_request('getUserProfilePhotos', _rectify(p))
'See: https://core.telegram.org/bots/api#getfile'
def getFile(self, file_id):
p = _strip(locals()) return self._api_request('getFile', _rectify(p))
'See: https://core.telegram.org/bots/api#kickchatmember'
def kickChatMember(self, chat_id, user_id, until_date=None):
p = _strip(locals()) return self._api_request('kickChatMember', _rectify(p))
'See: https://core.telegram.org/bots/api#unbanchatmember'
def unbanChatMember(self, chat_id, user_id):
p = _strip(locals()) return self._api_request('unbanChatMember', _rectify(p))
'See: https://core.telegram.org/bots/api#restrictchatmember'
def restrictChatMember(self, chat_id, user_id, until_date=None, can_send_messages=None, can_send_media_messages=None, can_send_other_messages=None, can_add_web_page_previews=None):
p = _strip(locals()) return self._api_request('restrictChatMember', _rectify(p))
'See: https://core.telegram.org/bots/api#promotechatmember'
def promoteChatMember(self, chat_id, user_id, can_change_info=None, can_post_messages=None, can_edit_messages=None, can_delete_messages=None, can_invite_users=None, can_restrict_members=None, can_pin_messages=None, can_promote_members=None):
p = _strip(locals()) return self._api_request('promoteChatMember', _rectify(p))
'See: https://core.telegram.org/bots/api#exportchatinvitelink'
def exportChatInviteLink(self, chat_id):
p = _strip(locals()) return self._api_request('exportChatInviteLink', _rectify(p))
'See: https://core.telegram.org/bots/api#setchatphoto'
def setChatPhoto(self, chat_id, photo):
p = _strip(locals(), more=['photo']) return self._api_request_with_file('setChatPhoto', _rectify(p), 'photo', photo)
'See: https://core.telegram.org/bots/api#deletechatphoto'
def deleteChatPhoto(self, chat_id):
p = _strip(locals()) return self._api_request('deleteChatPhoto', _rectify(p))
'See: https://core.telegram.org/bots/api#setchattitle'
def setChatTitle(self, chat_id, title):
p = _strip(locals()) return self._api_request('setChatTitle', _rectify(p))
'See: https://core.telegram.org/bots/api#setchatdescription'
def setChatDescription(self, chat_id, description=None):
p = _strip(locals()) return self._api_request('setChatDescription', _rectify(p))
'See: https://core.telegram.org/bots/api#pinchatmessage'
def pinChatMessage(self, chat_id, message_id, disable_notification=None):
p = _strip(locals()) return self._api_request('pinChatMessage', _rectify(p))
'See: https://core.telegram.org/bots/api#unpinchatmessage'
def unpinChatMessage(self, chat_id):
p = _strip(locals()) return self._api_request('unpinChatMessage', _rectify(p))
'See: https://core.telegram.org/bots/api#leavechat'
def leaveChat(self, chat_id):
p = _strip(locals()) return self._api_request('leaveChat', _rectify(p))
'See: https://core.telegram.org/bots/api#getchat'
def getChat(self, chat_id):
p = _strip(locals()) return self._api_request('getChat', _rectify(p))
'See: https://core.telegram.org/bots/api#getchatadministrators'
def getChatAdministrators(self, chat_id):
p = _strip(locals()) return self._api_request('getChatAdministrators', _rectify(p))
'See: https://core.telegram.org/bots/api#getchatmemberscount'
def getChatMembersCount(self, chat_id):
p = _strip(locals()) return self._api_request('getChatMembersCount', _rectify(p))
'See: https://core.telegram.org/bots/api#getchatmember'
def getChatMember(self, chat_id, user_id):
p = _strip(locals()) return self._api_request('getChatMember', _rectify(p))
'See: https://core.telegram.org/bots/api#answercallbackquery'
def answerCallbackQuery(self, callback_query_id, text=None, show_alert=None, url=None, cache_time=None):
p = _strip(locals()) return self._api_request('answerCallbackQuery', _rectify(p))
'See: https://core.telegram.org/bots/api#answershippingquery'
def answerShippingQuery(self, shipping_query_id, ok, shipping_options=None, error_message=None):
p = _strip(locals()) return self._api_request('answerShippingQuery', _rectify(p))
'See: https://core.telegram.org/bots/api#answerprecheckoutquery'
def answerPreCheckoutQuery(self, pre_checkout_query_id, ok, error_message=None):
p = _strip(locals()) return self._api_request('answerPreCheckoutQuery', _rectify(p))
'See: https://core.telegram.org/bots/api#editmessagetext :param msg_identifier: a 2-tuple (``chat_id``, ``message_id``), a 1-tuple (``inline_message_id``), or simply ``inline_message_id``. You may extract this value easily with :meth:`telepot.message_identifier`'
def editMessageText(self, msg_identifier, text, parse_mode=None, disable_web_page_preview=None, reply_markup=None):
p = _strip(locals(), more=['msg_identifier']) p.update(_dismantle_message_identifier(msg_identifier)) return self._api_request('editMessageText', _rectify(p))
'See: https://core.telegram.org/bots/api#editmessagecaption :param msg_identifier: Same as ``msg_identifier`` in :meth:`telepot.Bot.editMessageText`'
def editMessageCaption(self, msg_identifier, caption=None, reply_markup=None):
p = _strip(locals(), more=['msg_identifier']) p.update(_dismantle_message_identifier(msg_identifier)) return self._api_request('editMessageCaption', _rectify(p))
'See: https://core.telegram.org/bots/api#editmessagereplymarkup :param msg_identifier: Same as ``msg_identifier`` in :meth:`telepot.Bot.editMessageText`'
def editMessageReplyMarkup(self, msg_identifier, reply_markup=None):
p = _strip(locals(), more=['msg_identifier']) p.update(_dismantle_message_identifier(msg_identifier)) return self._api_request('editMessageReplyMarkup', _rectify(p))
'See: https://core.telegram.org/bots/api#deletemessage :param msg_identifier: Same as ``msg_identifier`` in :meth:`telepot.Bot.editMessageText`, except this method does not work on inline messages.'
def deleteMessage(self, msg_identifier):
p = _strip(locals(), more=['msg_identifier']) p.update(_dismantle_message_identifier(msg_identifier)) return self._api_request('deleteMessage', _rectify(p))
'See: https://core.telegram.org/bots/api#sendsticker :param sticker: Same as ``photo`` in :meth:`telepot.Bot.sendPhoto`'
def sendSticker(self, chat_id, sticker, disable_notification=None, reply_to_message_id=None, reply_markup=None):
p = _strip(locals(), more=['sticker']) return self._api_request_with_file('sendSticker', _rectify(p), 'sticker', sticker)
'See: https://core.telegram.org/bots/api#getstickerset'
def getStickerSet(self, name):
p = _strip(locals()) return self._api_request('getStickerSet', _rectify(p))
'See: https://core.telegram.org/bots/api#uploadstickerfile'
def uploadStickerFile(self, user_id, png_sticker):
p = _strip(locals(), more=['png_sticker']) return self._api_request_with_file('uploadStickerFile', _rectify(p), 'png_sticker', png_sticker)
'See: https://core.telegram.org/bots/api#createnewstickerset'
def createNewStickerSet(self, user_id, name, title, png_sticker, emojis, contains_masks=None, mask_position=None):
p = _strip(locals(), more=['png_sticker']) return self._api_request_with_file('createNewStickerSet', _rectify(p), 'png_sticker', png_sticker)
'See: https://core.telegram.org/bots/api#addstickertoset'
def addStickerToSet(self, user_id, name, png_sticker, emojis, mask_position=None):
p = _strip(locals(), more=['png_sticker']) return self._api_request_with_file('addStickerToSet', _rectify(p), 'png_sticker', png_sticker)
'See: https://core.telegram.org/bots/api#setstickerpositioninset'
def setStickerPositionInSet(self, sticker, position):
p = _strip(locals()) return self._api_request('setStickerPositionInSet', _rectify(p))
'See: https://core.telegram.org/bots/api#deletestickerfromset'
def deleteStickerFromSet(self, sticker):
p = _strip(locals()) return self._api_request('deleteStickerFromSet', _rectify(p))
'See: https://core.telegram.org/bots/api#answerinlinequery'
def answerInlineQuery(self, inline_query_id, results, cache_time=None, is_personal=None, next_offset=None, switch_pm_text=None, switch_pm_parameter=None):
p = _strip(locals()) return self._api_request('answerInlineQuery', _rectify(p))
'See: https://core.telegram.org/bots/api#getupdates'
def getUpdates(self, offset=None, limit=None, timeout=None, allowed_updates=None):
p = _strip(locals()) return self._api_request('getUpdates', _rectify(p))
'See: https://core.telegram.org/bots/api#setwebhook'
def setWebhook(self, url=None, certificate=None, max_connections=None, allowed_updates=None):
p = _strip(locals(), more=['certificate']) if certificate: files = {'certificate': certificate} return self._api_request('setWebhook', _rectify(p), files) else: return self._api_request('setWebhook', _rectify(p))
'See: https://core.telegram.org/bots/api#deletewebhook'
def deleteWebhook(self):
return self._api_request('deleteWebhook')
'See: https://core.telegram.org/bots/api#getwebhookinfo'
def getWebhookInfo(self):
return self._api_request('getWebhookInfo')
'See: https://core.telegram.org/bots/api#setgamescore :param game_message_identifier: Same as ``msg_identifier`` in :meth:`telepot.Bot.editMessageText`'
def setGameScore(self, user_id, score, game_message_identifier, force=None, disable_edit_message=None):
p = _strip(locals(), more=['game_message_identifier']) p.update(_dismantle_message_identifier(game_message_identifier)) return self._api_request('setGameScore', _rectify(p))
'See: https://core.telegram.org/bots/api#getgamehighscores :param game_message_identifier: Same as ``msg_identifier`` in :meth:`telepot.Bot.editMessageText`'
def getGameHighScores(self, user_id, game_message_identifier):
p = _strip(locals(), more=['game_message_identifier']) p.update(_dismantle_message_identifier(game_message_identifier)) return self._api_request('getGameHighScores', _rectify(p))
'Download a file to local disk. :param dest: a path or a ``file`` object'
def download_file(self, file_id, dest):
f = self.getFile(file_id) try: d = (dest if _isfile(dest) else open(dest, 'wb')) r = api.download((self._token, f['file_path']), preload_content=False) while 1: data = r.read(self._file_chunk_size) if (not data): break d.write(data) ...
':deprecated: will be removed in future. Use :class:`.MessageLoop` instead. Spawn a thread to constantly ``getUpdates`` or pull updates from a queue. Apply ``callback`` to every message received. Also starts the scheduler thread for internal events. :param callback: a function that takes one argument (the message), or ...
def message_loop(self, callback=None, relax=0.1, timeout=20, allowed_updates=None, source=None, ordered=True, maxhold=3, run_forever=False):
if (callback is None): callback = self.handle elif isinstance(callback, dict): callback = flavor_router(callback) collect_queue = queue.Queue() def collector(): while 1: try: item = collect_queue.get(block=True) callback(item) ...
':param delegation_patterns: a list of (seeder, delegator) tuples.'
def __init__(self, token, delegation_patterns):
super(DelegatorBot, self).__init__(token) self._delegate_records = [(p + ({},)) for p in delegation_patterns]
':type relax: float :param relax: seconds between each :meth:`.getUpdates` :type timeout: int :param timeout: ``timeout`` parameter supplied to :meth:`.getUpdates`, controlling how long to poll. :type allowed_updates: array of string :param allowed_updates: ``allowed_updates`` parameter supplied to :meth:`.getUpdates`,...
def run_forever(self, *args, **kwargs):
collectloop = CollectLoop(self._handle) updatesloop = GetUpdatesLoop(self._bot, (lambda update: collectloop.input_queue.put(_extract_message(update)[1]))) self._bot.scheduler.on_event(collectloop.input_queue.put) self._bot.scheduler.run_as_thread() updatesloop.run_as_thread(*args, **kwargs) coll...
':type maxhold: float :param maxhold: The maximum number of seconds an update is held waiting for a not-yet-arrived smaller ``update_id``. When this number of seconds is up, the update is delivered to the message-handling function even if some smaller ``update_id``\s have not yet arrived. If those smaller ``update_id``...
def run_forever(self, *args, **kwargs):
self._bot.scheduler.on_event(self._collectloop.input_queue.put) self._bot.scheduler.run_as_thread() self._orderer.run_as_thread(*args, **kwargs) self._collectloop.run_forever()
':param data: One of these: - ``str``, ``unicode`` (Python 2.7), or ``bytes`` (Python 3, decoded using UTF-8) representing a JSON-serialized `Update <https://core.telegram.org/bots/api#update>`_ object. - a ``dict`` representing an Update object.'
def feed(self, data):
update = _dictify(data) self._orderer.input_queue.put(update)
'Add a pattern to capture. :param pattern: a list of templates. A template may be a function that: - takes one argument - a message - returns ``True`` to indicate a match A template may also be a dictionary whose: - **keys** are used to *select* parts of message. Can be strings or regular expressions (as obtained by ``...
def capture(self, pattern):
self._patterns.append(pattern)
'Block until a matched message appears.'
def wait(self):
if (not self._patterns): raise RuntimeError('Listener has nothing to capture') while 1: msg = self._queue.get(block=True) if any(map((lambda p: filtering.match_all(msg, p)), self._patterns)): return msg
':param msg_identifier: a message identifier as mentioned above, or a message (whose identifier will be automatically extracted).'
def __init__(self, bot, msg_identifier):
if isinstance(msg_identifier, dict): msg_identifier = message_identifier(msg_identifier) for method in ['editMessageText', 'editMessageCaption', 'editMessageReplyMarkup', 'deleteMessage']: setattr(self, method, partial(getattr(bot, method), msg_identifier))