Skip to content

Update Examples with the str.format() syntax. #870

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 12 commits into from
Oct 20, 2017
Merged
1 change: 1 addition & 0 deletions AUTHORS.rst
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ The following wonderful people contributed directly or indirectly to this projec
- `Rahiel Kasim <https://github.com/rahiel>`_
- `Sascha <https://github.com/saschalalala>`_
- `Shelomentsev D <https://github.com/shelomentsevd>`_
- `Simon Schürrle <https://github.com/SitiSchu>`_
- `sooyhwang <https://github.com/sooyhwang>`_
- `thodnev <https://github.com/thodnev>`_
- `Valentijn <https://github.com/Faalentijn>`_
Expand Down
19 changes: 10 additions & 9 deletions examples/conversationbot.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ def start(bot, update):

def gender(bot, update):
user = update.message.from_user
logger.info("Gender of %s: %s" % (user.first_name, update.message.text))
logger.info("Gender of %s: %s", user.first_name, update.message.text)
update.message.reply_text('I see! Please send me a photo of yourself, '
'so I know what you look like, or send /skip if you don\'t want to.',
reply_markup=ReplyKeyboardRemove())
Expand All @@ -58,7 +58,7 @@ def photo(bot, update):
user = update.message.from_user
photo_file = bot.get_file(update.message.photo[-1].file_id)
photo_file.download('user_photo.jpg')
logger.info("Photo of %s: %s" % (user.first_name, 'user_photo.jpg'))
logger.info("Photo of %s: %s", user.first_name, 'user_photo.jpg')
update.message.reply_text('Gorgeous! Now, send me your location please, '
'or send /skip if you don\'t want to.')

Expand All @@ -67,7 +67,7 @@ def photo(bot, update):

def skip_photo(bot, update):
user = update.message.from_user
logger.info("User %s did not send a photo." % user.first_name)
logger.info("User %s did not send a photo.", user.first_name)
update.message.reply_text('I bet you look great! Now, send me your location please, '
'or send /skip.')

Expand All @@ -77,8 +77,8 @@ def skip_photo(bot, update):
def location(bot, update):
user = update.message.from_user
user_location = update.message.location
logger.info("Location of %s: %f / %f"
% (user.first_name, user_location.latitude, user_location.longitude))
logger.info("Location of %s: %f / %f", user.first_name, user_location.latitude,
user_location.longitude)
update.message.reply_text('Maybe I can visit you sometime! '
'At last, tell me something about yourself.')

Expand All @@ -87,7 +87,7 @@ def location(bot, update):

def skip_location(bot, update):
user = update.message.from_user
logger.info("User %s did not send a location." % user.first_name)
logger.info("User %s did not send a location.", user.first_name)
update.message.reply_text('You seem a bit paranoid! '
'At last, tell me something about yourself.')

Expand All @@ -96,23 +96,24 @@ def skip_location(bot, update):

def bio(bot, update):
user = update.message.from_user
logger.info("Bio of %s: %s" % (user.first_name, update.message.text))
logger.info("Bio of %s: %s", user.first_name, update.message.text)
update.message.reply_text('Thank you! I hope we can talk again some day.')

return ConversationHandler.END


def cancel(bot, update):
user = update.message.from_user
logger.info("User %s canceled the conversation." % user.first_name)
logger.info("User %s canceled the conversation.", user.first_name)
update.message.reply_text('Bye! I hope we can talk again some day.',
reply_markup=ReplyKeyboardRemove())

return ConversationHandler.END


def error(bot, update, error):
logger.warn('Update "%s" caused error "%s"' % (update, error))
"""Log Errors caused by Updates."""
logger.warning('Update "%s" caused error "%s"', update, error)


def main():
Expand Down
19 changes: 10 additions & 9 deletions examples/conversationbot2.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ def facts_to_str(user_data):
facts = list()

for key, value in user_data.items():
facts.append('%s - %s' % (key, value))
facts.append('{} - {}'.format(key, value))

return "\n".join(facts).join(['\n', '\n'])

Expand All @@ -58,7 +58,8 @@ def start(bot, update):
def regular_choice(bot, update, user_data):
text = update.message.text
user_data['choice'] = text
update.message.reply_text('Your %s? Yes, I would love to hear about that!' % text.lower())
update.message.reply_text(
'Your {}? Yes, I would love to hear about that!'.format(text.lower()))

return TYPING_REPLY

Expand All @@ -77,10 +78,9 @@ def received_information(bot, update, user_data):
del user_data['choice']

update.message.reply_text("Neat! Just so you know, this is what you already told me:"
"%s"
"You can tell me more, or change your opinion on something."
% facts_to_str(user_data),
reply_markup=markup)
"{}"
"You can tell me more, or change your opinion on something.".format(
facts_to_str(user_data)), reply_markup=markup)

return CHOOSING

Expand All @@ -90,15 +90,16 @@ def done(bot, update, user_data):
del user_data['choice']

update.message.reply_text("I learned these facts about you:"
"%s"
"Until next time!" % facts_to_str(user_data))
"{}"
"Until next time!".format(facts_to_str(user_data)))

user_data.clear()
return ConversationHandler.END


def error(bot, update, error):
logger.warn('Update "%s" caused error "%s"' % (update, error))
"""Log Errors caused by Updates."""
logger.warning('Update "%s" caused error "%s"', update, error)


def main():
Expand Down
13 changes: 9 additions & 4 deletions examples/echobot.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Simple Bot to reply to Telegram messages. This is built on the API wrapper, see
# echobot2.py to see the same example built on the telegram.ext bot framework.
# This program is dedicated to the public domain under the CC0 license.
"""Simple Bot to reply to Telegram messages.

This is built on the API wrapper, see echobot2.py to see the same example built
on the telegram.ext bot framework.
This program is dedicated to the public domain under the CC0 license.
"""
import logging
import telegram
from telegram.error import NetworkError, Unauthorized
Expand All @@ -12,7 +14,9 @@

update_id = None


def main():
"""Run the bot."""
global update_id
# Telegram Bot Authorization Token
bot = telegram.Bot('TOKEN')
Expand All @@ -37,6 +41,7 @@ def main():


def echo(bot):
"""Echo the message the user sent."""
global update_id
# Request updates after the last update_id
for update in bot.get_updates(offset=update_id, timeout=10):
Expand Down
16 changes: 11 additions & 5 deletions examples/echobot2.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Simple Bot to reply to Telegram messages
# This program is dedicated to the public domain under the CC0 license.
"""

"""Simple Bot to reply to Telegram messages.

This program is dedicated to the public domain under the CC0 license.

This Bot uses the Updater class to handle the bot.

First, a few handler functions are defined. Then, those functions are passed to
Expand All @@ -29,22 +30,27 @@
# Define a few command handlers. These usually take the two arguments bot and
# update. Error handlers also receive the raised TelegramError object in error.
def start(bot, update):
"""Send a message when the command /start is issued."""
update.message.reply_text('Hi!')


def help(bot, update):
"""Send a message when the command /help is issued."""
update.message.reply_text('Help!')


def echo(bot, update):
"""Echo the user message."""
update.message.reply_text(update.message.text)


def error(bot, update, error):
logger.warn('Update "%s" caused error "%s"' % (update, error))
"""Log Errors caused by Updates."""
logger.warning('Update "%s" caused error "%s"', update, error)


def main():
"""Start the bot."""
# Create the EventHandler and pass it your bot's token.
updater = Updater("TOKEN")

Expand Down
59 changes: 30 additions & 29 deletions examples/inlinebot.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Simple Bot to reply to Telegram messages
# This program is dedicated to the public domain under the CC0 license.
"""

"""Simple Bot to reply to Telegram messages.

This program is dedicated to the public domain under the CC0 license.

This Bot uses the Updater class to handle the bot.

First, a few handler functions are defined. Then, those functions are passed to
Expand All @@ -19,6 +20,8 @@

import re

from telegram.utils.helpers import escape_markdown

from telegram import InlineQueryResultArticle, ParseMode, \
InputTextMessageContent
from telegram.ext import Updater, InlineQueryHandler, CommandHandler
Expand All @@ -34,45 +37,43 @@
# Define a few command handlers. These usually take the two arguments bot and
# update. Error handlers also receive the raised TelegramError object in error.
def start(bot, update):
"""Send a message when the command /start is issued."""
update.message.reply_text('Hi!')


def help(bot, update):
"""Send a message when the command /help is issued."""
update.message.reply_text('Help!')


def escape_markdown(text):
"""Helper function to escape telegram markup symbols"""
escape_chars = '\*_`\['
return re.sub(r'([%s])' % escape_chars, r'\\\1', text)


def inlinequery(bot, update):
"""Handle the inline query."""
query = update.inline_query.query
results = list()

results.append(InlineQueryResultArticle(id=uuid4(),
title="Caps",
input_message_content=InputTextMessageContent(
query.upper())))

results.append(InlineQueryResultArticle(id=uuid4(),
title="Bold",
input_message_content=InputTextMessageContent(
"*%s*" % escape_markdown(query),
parse_mode=ParseMode.MARKDOWN)))

results.append(InlineQueryResultArticle(id=uuid4(),
title="Italic",
input_message_content=InputTextMessageContent(
"_%s_" % escape_markdown(query),
parse_mode=ParseMode.MARKDOWN)))
results = [
InlineQueryResultArticle(
id=uuid4(),
title="Caps",
input_message_content=InputTextMessageContent(
query.upper())),
InlineQueryResultArticle(
id=uuid4(),
title="Bold",
input_message_content=InputTextMessageContent(
"*{}*".format(escape_markdown(query)),
parse_mode=ParseMode.MARKDOWN)),
InlineQueryResultArticle(
id=uuid4(),
title="Italic",
input_message_content=InputTextMessageContent(
"_{}_".format(escape_markdown(query)),
parse_mode=ParseMode.MARKDOWN))]

update.inline_query.answer(results)


def error(bot, update, error):
logger.warning('Update "%s" caused error "%s"' % (update, error))
"""Log Errors caused by Updates."""
logger.warning('Update "%s" caused error "%s"', update, error)


def main():
Expand Down
39 changes: 23 additions & 16 deletions examples/inlinekeyboard.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Basic example for a bot that uses inline keyboards.
# This program is dedicated to the public domain under the CC0 license.
"""Basic example for a bot that uses inline keyboards.

# This program is dedicated to the public domain under the CC0 license.
"""
import logging
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Updater, CommandHandler, CallbackQueryHandler

logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)


def start(bot, update):
Expand All @@ -26,7 +27,7 @@ def start(bot, update):
def button(bot, update):
query = update.callback_query

bot.edit_message_text(text="Selected option: %s" % query.data,
bot.edit_message_text(text="Selected option: {}".format(query.data),
chat_id=query.message.chat_id,
message_id=query.message.message_id)

Expand All @@ -36,20 +37,26 @@ def help(bot, update):


def error(bot, update, error):
logging.warning('Update "%s" caused error "%s"' % (update, error))
"""Log Errors caused by Updates."""
logger.warning('Update "%s" caused error "%s"', update, error)


def main():
# Create the Updater and pass it your bot's token.
updater = Updater("TOKEN")

updater.dispatcher.add_handler(CommandHandler('start', start))
updater.dispatcher.add_handler(CallbackQueryHandler(button))
updater.dispatcher.add_handler(CommandHandler('help', help))
updater.dispatcher.add_error_handler(error)

# Create the Updater and pass it your bot's token.
updater = Updater("TOKEN")
# Start the Bot
updater.start_polling()

updater.dispatcher.add_handler(CommandHandler('start', start))
updater.dispatcher.add_handler(CallbackQueryHandler(button))
updater.dispatcher.add_handler(CommandHandler('help', help))
updater.dispatcher.add_error_handler(error)
# Run the bot until the user presses Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT
updater.idle()

# Start the Bot
updater.start_polling()

# Run the bot until the user presses Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT
updater.idle()
if __name__ == '__main__':
main()
Loading
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy