8000 Updating the examples by Poolitzer · Pull Request #2937 · python-telegram-bot/python-telegram-bot · GitHub
[go: up one dir, main page]

Skip to content

Updating the examples #2937

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 15 commits into from
Apr 10, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ repos:
args:
- --diff
- --check
additional_dependencies:
- click==8.0.2
- repo: https://gitlab.com/pycqa/flake8
rev: 4.0.1
hooks:
Expand Down Expand Up @@ -44,6 +46,18 @@ repos:
- APScheduler==3.6.3
- cachetools==4.2.2
- . # this basically does `pip install -e .`n
- id: mypy
name: mypy-examples
files: ^examples/.*\.py$
args:
- --no-strict-optional
- --follow-imports=silent
additional_dependencies:
- certifi
- tornado>=6.1
- APScheduler==3.6.3
- cachetools==4.2.2
- . # this basically does `pip install -e .`
- repo: https://github.com/asottile/pyupgrade
rev: v2.29.0
hooks:
Expand Down
10 changes: 5 additions & 5 deletions examples/arbitrarycallbackdatabot.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,13 +97,13 @@ def main() -> None:
.build()
)

application.application.add_handler(CommandHandler('start', start))
application.application.add_handler(CommandHandler('help', help_command))
application.application.add_handler(CommandHandler('clear', clear))
application.application.add_handler(
application.add_handler(CommandHandler('start', start))
application.add_handler(CommandHandler('help', help_command))
application.add_handler(CommandHandler('clear', clear))
application.add_handler(
CallbackQueryHandler(handle_invalid_button, pattern=InvalidCallbackData)
)
application.application.add_handler(CallbackQueryHandler(list_button))
application.add_handler(CallbackQueryHandler(list_button))

# Run the bot until the user presses Ctrl-C
application.run_polling()
Expand Down
6 changes: 3 additions & 3 deletions examples/chatmemberbot.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,12 +127,12 @@ async def greet_chat_members(update: Update, context: CallbackContext.DEFAULT_TY
member_name = update.chat_member.new_chat_member.user.mention_html()

if not was_member and is_member:
update.effective_chat.send_message(
await update.effective_chat.send_message(
f"{member_name} was added by {cause_name}. Welcome!",
parse_mode=ParseMode.HTML,
)
elif was_member and not is_member:
update.effective_chat.send_message(
await update.effective_chat.send_message(
f"{member_name} is no longer with us. Thanks a lot, {cause_name} ...",
parse_mode=ParseMode.HTML,
)
Expand All @@ -153,7 +153,7 @@ def main() -> None:
# Run the bot until the user presses Ctrl-C
# We pass 'allowed_updates' handle *all* updates including `chat_member` updates
# To reset this, simply pass `allowed_updates=[]`
application.run_polling()(allowed_updates=Update.ALL_TYPES)
application.run_polling(allowed_updates=Update.ALL_TYPES)


if __name__ == "__main__":
Expand Down
10 changes: 8 additions & 2 deletions examples/contexttypesbot.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
bot.
"""

import logging
from collections import defaultdict
from typing import DefaultDict, Optional, Set

Expand All @@ -25,6 +26,12 @@
Application,
)

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


class ChatData:
"""Custom class for chat_data. Here we store data per message."""
Expand Down Expand Up @@ -88,7 +95,7 @@ async def count_click(update: Update, context: CustomContext) -> None:
"""Update the click count for the message."""
context.message_clicks += 1
await update.callback_query.answer()
update.effective_message.edit_text(
await update.effective_message.edit_text(
f'This button was clicked <i>{context.message_clicks}</i> times.',
reply_markup=InlineKeyboardMarkup.from_button(
InlineKeyboardButton(text='Click me!', callback_data='button')
Expand Down Expand Up @@ -116,7 +123,6 @@ def main() -> None:
context_types = ContextTypes(context=CustomContext, chat_data=ChatData)
application = Application.builder().token("TOKEN").context_types(context_types).build()

application = application.application
# run track_users in its own group to not interfere with the user handlers
application.add_handler(TypeHandler(Update, track_users), group=-1)
application.add_handler(CommandHandler("start", start))
Expand Down
2 changes: 1 addition & 1 deletion examples/conversationbot.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ async def photo(update: Update, context: CallbackContext.DEFAULT_TYPE) -> int:
"""Stores the photo and asks for a location."""
user = update.message.from_user
photo_file = await update.message.photo[-1].get_file()
photo_file.download('user_photo.jpg')
await photo_file.download('user_photo.jpg')
logger.info("Photo of %s: %s", user.first_name, 'user_photo.jpg')
await update.message.reply_text(
'Gorgeous! Now, send me your location please, or send /skip if you don\'t want to.'
Expand Down
2 changes: 1 addition & 1 deletion examples/conversationbot2.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ async def received_information(update: Update, context: CallbackContext.DEFAULT_

await update.message.reply_text(
"Neat! Just so you know, this is what you already told me:"
f"{facts_to_str(user_data)} You can tell me more, or change your opinion"
f"{facts_to_str(user_data)}You can tell me more, or change your opinion"
" on something.",
reply_markup=markup,
)
Expand Down
6 changes: 2 additions & 4 deletions examples/deeplinking.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,10 +73,8 @@ async def deep_linked_level_2(update: Update, context: CallbackContext.DEFAULT_T
"""Reached through the SO_COOL payload"""
bot = context.bot
url = helpers.create_deep_linked_url(bot.username, USING_ENTITIES)
text = f"You can also mask the deep-linked URLs as links: [▶️ CLICK HERE]({url})."
await update.message.reply_text(
text, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True
)
text = f"You can also mask the deep-linked URLs as links: <a href=\"{url}\">▶️ CLICK HERE</a>."
await update.message.reply_text(text, parse_mode=ParseMode.HTML, disable_web_page_preview=True)


async def deep_linked_level_3(update: Update, context: CallbackContext.DEFAULT_TYPE) -> None:
Expand Down
4 changes: 2 additions & 2 deletions examples/echobot.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@
async def start(update: Update, context: CallbackContext.DEFAULT_TYPE) -> None:
"""Send a message when the command /start is issued."""
user = update.effective_user
await update.message.reply_markdown_v2(
fr'Hi {user.mention_markdown_v2()}\!',
await update.message.reply_html(
fr'Hi {user.mention_html()}!',
reply_markup=ForceReply(selective=True),
)

Expand Down
8 changes: 1 addition & 7 deletions examples/errorhandlerbot.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,6 @@
)
logger = logging.getLogger(__name__)

# The token you got from @botfather when you created the bot
BOT_TOKEN = "TOKEN"

# This can be your own ID, or one for a developer group/channel.
# You can use the /start command of this bot to see your chat id.
DEVELOPER_CHAT_ID = 123456789
Expand Down Expand Up @@ -70,10 +67,7 @@ async def start(update: Update, context: CallbackContext.DEFAULT_TYPE) -> None:
def main() -> None:
"""Run the bot."""
# Create the Application and pass it your bot's token.
application = Application.builder().token(BOT_TOKEN).build()

# Get the application to register handlers
application = application.application
application = Application.builder().token("TOKEN").build()

# Register the commands...
application.add_handler(CommandHandler('start', start))
Expand Down
14 changes: 7 additions & 7 deletions examples/inlinebot.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,10 @@
"""
import logging
from uuid import uuid4
from html import escape

from telegram import InlineQueryResultArticle, InputTextMessageContent, Update
from telegram.constants import ParseMode
from telegram.helpers import escape_markdown
from telegram.ext import Application, InlineQueryHandler, CommandHandler, CallbackContext

# Enable logging
Expand All @@ -28,7 +28,7 @@


# Define a few command handlers. These usually take the two arguments update and
# context. Error handlers also receive the raised TelegramError object in error.
# context.
async def start(update: Update, context: CallbackContext.DEFAULT_TYPE) -> None:
"""Send a message when the command /start is issued."""
await update.message.reply_text('Hi!')
Expand All @@ -39,8 +39,8 @@ async def help_command(update: Update, context: CallbackContext.DEFAULT_TYPE) ->
await update.message.reply_text('Help!')


async def inlinequery(update: Update, context: CallbackContext.DEFAULT_TYPE) -> None:
"""Handle the inline query."""
async def inline_query(update: Update, context: CallbackContext.DEFAULT_TYPE) -> None:
"""Handle the inline query. This is run when you type: @botusername <query>"""
query = update.inline_query.query

if query == "":
Expand All @@ -56,14 +56,14 @@ async def inlinequery(update: Update, context: CallbackContext.DEFAULT_TYPE) ->
id=str(uuid4()),
title="Bold",
input_message_content=InputTextMessageContent(
f"*{escape_markdown(query)}*", parse_mode=ParseMode.MARKDOWN
f"<b>{escape(query)}</b>", parse_mode=ParseMode.HTML
),
),
InlineQueryResultArticle(
id=str(uuid4()),
title="Italic",
input_message_content=InputTextMessageContent(
f"_{escape_markdown(query)}_", parse_mode=ParseMode.MARKDOWN
f"<i>{escape(query)}</i>", parse_mode=ParseMode.HTML
),
),
]
Expand All @@ -81,7 +81,7 @@ def main() -> None:
application.add_handler(CommandHandler("help", help_command))

# on non command i.e message - echo the message on Telegram
application.add_handler(InlineQueryHandler(inlinequery))
application.add_handler(InlineQueryHandler(inline_query))

# Run the bot until the user presses Ctrl-C
application.run_polling()
Expand Down
6 changes: 3 additions & 3 deletions examples/inlinekeyboard.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,9 @@ def main() -> None:
# Create the Application and pass it your bot's token.
application = Application.builder().token("TOKEN").build()

application.application.add_handler(CommandHandler('start', start))
application.application.add_handler(CallbackQueryHandler(button))
application.application.add_handler(CommandHandler('help', help_command))
application.add_handler(CommandHandler('start', start))
application.add_handler(CallbackQueryHandler(button))
application.add_handler(CommandHandler('help', help_command))

# Run the bot until the user presses Ctrl-C
application.run_polling()
Expand Down
20 changes: 10 additions & 10 deletions examples/inlinekeyboard2.py
text="First CallbackQueryHandler, Choose a route", reply_markup=reply_markup
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
logger = logging.getLogger(__name__)

# Stages
FIRST, SECOND = range(2)
START_ROUTES, END_ROUTES = range(2)
# Callback data
ONE, TWO, THREE, FOUR = range(4)

Expand All @@ -56,7 +56,7 @@ async def start(update: Update, context: CallbackContext.DEFAULT_TYPE) -> int:
# Send message with text and appended InlineKeyboard
await update.message.reply_text("Start handler, Choose a route", reply_markup=reply_markup)
# Tell ConversationHandler that we're in state `FIRST` now
return FIRST
return START_ROUTES


async def start_over(update: Update, context: CallbackContext.DEFAULT_TYPE) -> int:
Expand All @@ -77,7 +77,7 @@ async def start_over(update: Update, context: CallbackContext.DEFAULT_TYPE) -> i
# originated the CallbackQuery. This gives the feeling of an
# interactive menu.
await query.edit_message_text(text="Start handler, Choose a route", reply_markup=reply_markup)
return FIRST
return START_ROUTES


async def one(update: Update, context: CallbackContext.DEFAULT_TYPE) -> int:
Expand All @@ -94,7 +94,7 @@ async def one(update: Update, context: CallbackContext.DEFAULT_TYPE) -> int:
await query.edit_message_text(
)
return FIRST
return START_ROUTES


async def two(update: Update, context: CallbackContext.DEFAULT_TYPE) -> int:
Expand All @@ -111,11 +111,11 @@ async def two(update: Update, context: CallbackContext.DEFAULT_TYPE) -> int:
await query.edit_message_text(
text="Second CallbackQueryHandler, Choose a route", reply_markup=reply_markup
)
return FIRST
return START_ROUTES


async def three(update: Update, context: CallbackContext.DEFAULT_TYPE) -> int:
"""Show new choice of buttons"""
"""Show new choice of buttons. This is the end point of the conversation."""
query = update.callback_query
await query.answer()
keyboard = [
Expand All @@ -129,7 +129,7 @@ async def three(update: Update, context: CallbackContext.DEFAULT_TYPE) -> int:
text="Third CallbackQueryHandler. Do want to start over?", reply_markup=reply_markup
)
# Transfer to conversation state `SECOND`
return SECOND
return END_ROUTES


async def four(update: Update, context: CallbackContext.DEFAULT_TYPE) -> int:
Expand All @@ -146,7 +146,7 @@ async def four(update: Update, context: CallbackContext.DEFAULT_TYPE) -> int:
await query.edit_message_text(
text="Fourth CallbackQueryHandler, Choose a route", reply_markup=reply_markup
)
return FIRST
return START_ROUTES


async def end(update: Update, context: CallbackContext.DEFAULT_TYPE) -> int:
Expand All @@ -173,13 +173,13 @@ def main() -> None:
conv_handler = ConversationHandler(
entry_points=[CommandHandler('start', start)],
states={
FIRST: [
START_ROUTES: [
CallbackQueryHandler(one, pattern='^' + str(ONE) + '$'),
CallbackQueryHandler(two, pattern='^' + str(TWO) + '$'),
CallbackQueryHandler(three, pattern='^' + str(THREE) + '$'),
CallbackQueryHandler(four, pattern='^' + str(FOUR) + '$'),
],
SECOND: [
END_ROUTES: [
CallbackQueryHandler(start_over, pattern='^' + str(ONE) + '$'),
CallbackQueryHandler(end, pattern='^' + str(TWO) + '$'),
],
Expand Down
24 changes: 13 additions & 11 deletions examples/nestedconversationbot.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,27 +120,29 @@ async def adding_self(update: Update, context: CallbackContext.DEFAULT_TYPE) ->
async def show_data(update: Update, context: CallbackContext.DEFAULT_TYPE) -> str:
"""Pretty print gathered data."""

def prettyprint(user_data: Dict[str, Any], level: str) -> str:
people = user_data.get(level)
def pretty_print(data: Dict[str, Any], level: str) -> str:
people = data.get(level)
if not people:
return '\nNo information yet.'

text = ''
return_str = ''
if level == SELF:
for person in user_data[level]:
text += f"\nName: {person.get(NAME, '-')}, Age: {person.get(AGE, '-')}"
for person in data[level]:
return_str += f"\nName: {person.get(NAME, '-')}, Age: {person.get(AGE, '-')}"
else:
male, female = _name_switcher(level)

for person in user_data[level]:
for person in data[level]:
gender = female if person[GENDER] == FEMALE else male
text += f"\n{gender}: Name: {person.get(NAME, '-')}, Age: {person.get(AGE, '-')}"
return text
return_str += (
f"\n{gender}: Name: {person.get(NAME, '-')}, Age: {person.get(AGE, '-')}"
)
return return_str

user_data = context.user_data
text = f"Yourself:{prettyprint(user_data, SELF)}"
text += f"\n\nParents:{prettyprint(user_data, PARENTS)}"
text += f"\n\nChildren:{prettyprint(user_data, CHILDREN)}"
text = f"Yourself:{pretty_print(user_data, SELF)}"
text += f"\n\nParents:{pretty_print(user_data, PARENTS)}"
text += f"\n\nChildren:{pretty_print(user_data, CHILDREN)}"

buttons = [[InlineKeyboardButton(text='Back', callback_data=str(END))]]
keyboard = InlineKeyboardMarkup(buttons)
Expand Down
Loading
0