本文整理汇总了Python中telegram.Update.de_json方法的典型用法代码示例。如果您正苦于以下问题:Python Update.de_json方法的具体用法?Python Update.de_json怎么用?Python Update.de_json使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类telegram.Update
的用法示例。
在下文中一共展示了Update.de_json方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: getUpdates
# 需要导入模块: from telegram import Update [as 别名]
# 或者: from telegram.Update import de_json [as 别名]
def getUpdates(self, offset=None, limit=100, timeout=0):
"""Use this method to receive incoming updates using long polling.
Args:
offset:
Identifier of the first update to be returned. Must be greater by
one than the highest among the identifiers of previously received
updates. By default, updates starting with the earliest unconfirmed
update are returned. An update is considered confirmed as soon as
getUpdates is called with an offset higher than its update_id.
limit:
Limits the number of updates to be retrieved. Values between 1—100
are accepted. Defaults to 100.
timeout:
Timeout in seconds for long polling. Defaults to 0, i.e. usual
short polling.
Returns:
A list of telegram.Update objects are returned.
"""
url = "%s/getUpdates" % (self.base_url)
data = {}
if offset:
data["offset"] = offset
if limit:
data["limit"] = limit
if timeout:
data["timeout"] = timeout
json_data = self._requestUrl(url, "POST", data=data)
data = self._parseAndCheckTelegram(json_data)
return [Update.de_json(x) for x in data]
示例2: post
# 需要导入模块: from telegram import Update [as 别名]
# 或者: from telegram.Update import de_json [as 别名]
def post(self, request, token):
dispatcher = self.get_dispatcher(token)
if not dispatcher:
return Http404()
json_string = request.body.decode('utf-8')
update = Update.de_json(json.loads(json_string))
dispatcher.process_update(update)
return HttpResponse()
示例3: __init__
# 需要导入模块: from telegram import Update [as 别名]
# 或者: from telegram.Update import de_json [as 别名]
def __init__(self):
update = Update.de_json(request.get_json(force=True))
if getattr(update, 'message', None):
for t, c in self.types.items():
if getattr(update.message, t):
m = c()
m.update = update
m.parse()
m.run()
m.respond()
示例4: getUpdates
# 需要导入模块: from telegram import Update [as 别名]
# 或者: from telegram.Update import de_json [as 别名]
def getUpdates(self,
offset=None,
limit=100,
timeout=0,
network_delay=.2):
"""Use this method to receive incoming updates using long polling.
Args:
offset:
Identifier of the first update to be returned. Must be greater by
one than the highest among the identifiers of previously received
updates. By default, updates starting with the earliest unconfirmed
update are returned. An update is considered confirmed as soon as
getUpdates is called with an offset higher than its update_id.
limit:
Limits the number of updates to be retrieved. Values between 1-100
are accepted. Defaults to 100.
timeout:
Timeout in seconds for long polling. Defaults to 0, i.e. usual
short polling.
network_delay:
Additional timeout in seconds to allow the response from Telegram
to take some time when using long polling. Defaults to 2, which
should be enough for most connections. Increase it if it takes very
long for data to be transmitted from and to the Telegram servers.
Returns:
list[:class:`telegram.Update`]: A list of :class:`telegram.Update`
objects are returned.
Raises:
:class:`telegram.TelegramError`
"""
url = '{0}/getUpdates'.format(self.base_url)
data = {'timeout': timeout}
if offset:
data['offset'] = offset
if limit:
data['limit'] = limit
urlopen_timeout = timeout + network_delay
result = request.post(url, data, timeout=urlopen_timeout)
if result:
self.logger.debug(
'Getting updates: %s', [u['update_id'] for u in result])
else:
self.logger.debug('No new updates found.')
return [Update.de_json(x) for x in result]
示例5: webhook
# 需要导入模块: from telegram import Update [as 别名]
# 或者: from telegram.Update import de_json [as 别名]
def webhook():
if request.method == "POST":
# retrieve the message in JSON and then transform it to Telegram object
update = Update.de_json(request.get_json(force=True))
logger.info("Update received! "+ update.message.text)
dp.process_update(update)
update_queue.put(update)
return "OK"
else:
return redirect("https://telegram.me/links_forward_bot", code=302)
示例6: send_message
# 需要导入模块: from telegram import Update [as 别名]
# 或者: from telegram.Update import de_json [as 别名]
def send_message(self, text, from_user_id=0, skip_answer=True):
update = {
'update_id': 0,
'message': {
'message_id': 0,
'text': text,
'from': {
'id': from_user_id,
'first_name': 'Jack'
},
'date': int(time.time())
}
}
self.updater.dispatcher.processUpdate(Update.de_json(update))
if skip_answer and len(self.bot.messages) > 0:
self.bot.pop_message()
示例7: application
# 需要导入模块: from telegram import Update [as 别名]
# 或者: from telegram.Update import de_json [as 别名]
def application(environ, start_response):
print "app"
# the environment variable CONTENT_LENGTH may be empty or missing
try:
request_body_size = int(environ.get('CONTENT_LENGTH', 0))
except (ValueError):
request_body_size = 0
# When the method is POST the variable will be sent
# in the HTTP request body which is passed by the WSGI server
# in the file like wsgi.input environment variable.
buf = environ['wsgi.input'].read(request_body_size)
global job_queue
updater = Updater("207443777:AAGuMP5nIJMqbFKILRmVuuAz8in7PfiWdjA")
job_queue = updater.job_queue
# Get the dispatcher to register handlers
dp = updater.dispatcher
# on different commands - answer in Telegram
dp.addHandler(CommandHandler("start", start))
dp.addHandler(CommandHandler("help", start))
dp.addHandler(CommandHandler("set", set))
dp.addHandler(InlineQueryHandler(inlinequery))
# log all errors
dp.addErrorHandler(error)
updater.bot.setWebhook("https://afternoon-shelf-83103.herokuapp.com")
# Start the Bot
#updater.start_polling()
json_string = bytes_to_native_str(buf)
update = Update.de_json(json.loads(json_string))
dp.processUpdate(update)
start_response('200 OK', [('Content-Type', 'text/plain')])
return ['']
# Block until the you presses Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT. This should be used most of the time, since
# start_polling() is non-blocking and will stop the bot gracefully.
import time
示例8: getUpdates
# 需要导入模块: from telegram import Update [as 别名]
# 或者: from telegram.Update import de_json [as 别名]
def getUpdates(self,
offset=None,
limit=100,
timeout=0):
"""Use this method to receive incoming updates using long polling.
Args:
offset:
Identifier of the first update to be returned. Must be greater by
one than the highest among the identifiers of previously received
updates. By default, updates starting with the earliest unconfirmed
update are returned. An update is considered confirmed as soon as
getUpdates is called with an offset higher than its update_id.
limit:
Limits the number of updates to be retrieved. Values between 1-100
are accepted. Defaults to 100.
timeout:
Timeout in seconds for long polling. Defaults to 0, i.e. usual
short polling.
Returns:
A list of telegram.Update objects are returned.
"""
url = '%s/getUpdates' % self.base_url
data = {}
if offset:
data['offset'] = offset
if limit:
data['limit'] = limit
if timeout:
data['timeout'] = timeout
result = request.post(url, data)
if result:
self.logger.info(
'Getting updates: %s', [u['update_id'] for u in result])
else:
self.logger.info('No new updates found.')
return [Update.de_json(x) for x in result]
示例9: post
# 需要导入模块: from telegram import Update [as 别名]
# 或者: from telegram.Update import de_json [as 别名]
def post(self, request, token):
serializer = UpdateSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
try:
bot = Bot.objects.get(token=token)
bot.handle(Update.de_json(request.data))
except Bot.DoesNotExist:
logger.warning("Token %s not associated to a bot" % token)
return Response(serializer.errors, status=status.HTTP_404_NOT_FOUND)
except:
exc_info = sys.exc_info()
traceback.print_exception(*exc_info)
logger.error("Error processing %s for token %s" % (request.data, token))
return Response(serializer.errors, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
else:
return Response(serializer.data, status=status.HTTP_200_OK)
logger.error("Validation error: %s from message %s" % (serializer.errors, request.data))
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
示例10: message
# 需要导入模块: from telegram import Update [as 别名]
# 或者: from telegram.Update import de_json [as 别名]
def message():
if request.method == 'POST':
if not out_channel.get_me()['username'] == self.verify:
logger.debug("Invalid access token, check it "
"matches Telegram")
return "failed"
update = Update.de_json(request.get_json(force=True),
out_channel)
if self._is_button(update):
message = update.callback_query.message
text = update.callback_query.data
else:
message = update.message
if self._is_user_message(message):
text = message.text.replace('/bot', '')
elif self._is_location(message):
text = ('{{"lng":{0}, "lat":{1}}}'
''.format(message.location.longitude,
message.location.latitude))
else:
return "success"
sender_id = message.chat.id
try:
if text == '_restart' or text == '/restart':
on_new_message(UserMessage(text, out_channel,
sender_id))
on_new_message(UserMessage('/start', out_channel,
sender_id))
else:
on_new_message(UserMessage(text, out_channel,
sender_id))
except Exception as e:
logger.error("Exception when trying to handle "
"message.{0}".format(e))
logger.error(e, exc_info=True)
if self.debug_mode:
raise
pass
return "success"
示例11: do_POST
# 需要导入模块: from telegram import Update [as 别名]
# 或者: from telegram.Update import de_json [as 别名]
def do_POST(self):
self.logger.debug("Webhook triggered")
try:
self._validate_post()
clen = self._get_content_len()
except _InvalidPost as e:
self.send_error(e.http_code)
self.end_headers()
else:
buf = self.rfile.read(clen)
json_string = bytes_to_native_str(buf)
self.send_response(200)
self.end_headers()
self.logger.debug("Webhook received data: " + json_string)
update = Update.de_json(json.loads(json_string))
self.logger.info("Received Update with ID %d on Webhook" % update.update_id)
self.server.update_queue.put(update)
示例12: do_POST
# 需要导入模块: from telegram import Update [as 别名]
# 或者: from telegram.Update import de_json [as 别名]
def do_POST(self):
self.logger.debug("Webhook triggered")
if self.path == self.server.webhook_path and \
'content-type' in self.headers and \
'content-length' in self.headers and \
self.headers['content-type'] == 'application/json':
json_string = \
n(self.rfile.read(int(self.headers['content-length'])))
self.send_response(200)
self.end_headers()
self.logger.debug("Webhook received data: " + json_string)
update = Update.de_json(json.loads(json_string))
self.logger.info("Received Update with ID %d on Webhook" %
update.update_id)
self.server.update_queue.put(update)
else:
self.send_error(403)
self.end_headers()
示例13: telegramWebHook
# 需要导入模块: from telegram import Update [as 别名]
# 或者: from telegram.Update import de_json [as 别名]
def telegramWebHook():
update = Update.de_json(request.get_json(force=True))
text = None
if getattr(update.message, 'document'):
gallery = Gallery().search(tgid = update.message.chat.id)
if gallery:
newfile = bot.getFile(update.message.document.file_id)
file_name = update.message.document.file_id
newfile.download(file_name)
writed = False
if os.path.exists(file_name):
writed = write_file(file_name, read_file(file_name, storage = 'local', append_path = False), acl = 'public-read', mime_type = update.message.document.mime_type)
thumbnail(file_name)
os.remove(file_name)
write_file('%s.json' % file_name, update.to_json())
if writed:
file_id = File(gallery_eid = gallery.eid, file_id = update.message.document.file_id)
file_id.save()
sendLink = getattr(gallery, 'sendLink', None)
if sendLink == 'True':
text = 'File URL: %s' % url_for('image', file_id = file_id.eid, _external = True, disable_web_page_preview = True)
else:
text = 'Failed to download file'
else:
text = 'Gallery does not exist, please create first'
pass
if getattr(update.message, 'text'):
args = update.message.text.split(' ', 2)
if args[0] == '/register':
text = 'Username:'
user = User().search(tgid = update.message.from_user.id)
if not user:
User(tgid = update.message.from_user.id).save()
text = 'Complete register: https://telegram.me/ACSGalleryBot?start=%s' % update.message.from_user.id
else:
text = 'User added to gallery'
# set gallery permission at this point because i have chat id
elif args[0] == '/start':
if len(args) > 1 and int(args[1]) == int(update.message.chat.id):
text = 'Username:'
bot.sendMessage(update.message.from_user.id, text, reply_markup = { 'force_reply' : True })
else:
text = update.to_json()
elif getattr(update.message, 'reply_to_message'):
if update.message.reply_to_message.text == 'Username:':
user = User().search(tgid = update.message.from_user.id)
if user:
user.username = update.message.text
user.save()
bot.sendMessage(update.message.chat.id, 'Password:', reply_markup = { 'force_reply' : True })
return 'ok'
elif update.message.reply_to_message.text == 'Password:':
user = User().search(tgid = update.message.from_user.id)
user.password = update.message.text
user.save()
text = 'User succesfuly registered'
elif args[0] == '/create':
if hasattr(update.message.chat, 'title'):
gallery = Gallery().search(tgid = update.message.chat.id)
if not gallery:
gallery = Gallery(tgid = update.message.chat.id, title = update.message.chat.title).save()
text = 'Gallery URL: %s' % url_for('gallery', id = gallery.eid, _external = True, _scheme = 'https')
else:
text = 'Bot only works in groups'
elif args[0] == '/remove':
gallery = Gallery().search(tgid = update.message.chat.id)
if gallery:
gallery.delete()
text = 'Gallery deleted'
else:
text = 'Gallery is not registered'
# TODO: Confirm
elif args[0] == '/config':
args.pop(0)
gallery = Gallery.search(tgid = update.message.chat.id)
if gallery:
if len(args) == 0:
text = g.config(update.message.chat.id)
elif len(args) == 1:
text = 'get one'
text = g.config(update.message.chat.id, args[0])
else:
text = g.config(update.message.chat.id, args[0], args[1])
else:
text = 'Gallery is not registered'
#else:
# text = update.to_json()
if text:
bot.sendMessage(update.message.chat.id, text, disable_web_page_preview=True)
return ""
示例14: telegram_hook
# 需要导入模块: from telegram import Update [as 别名]
# 或者: from telegram.Update import de_json [as 别名]
def telegram_hook(token):
if token != WEBHOOK_TOKEN:
abort(401, 'Unauthorized')
update = Update.de_json(request.json, bot)
if update.callback_query:
return process_callback(update.callback_query)
elif update.message:
return process_message(update.message)