Skip to content
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
3 changes: 2 additions & 1 deletion examples/chatmemberbot.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@ def extract_status_change(
) -> Optional[Tuple[bool, bool]]:
"""Takes a ChatMemberUpdated instance and extracts whether the 'old_chat_member' was a member
of the chat and whether the 'new_chat_member' is a member of the chat. Returns None, if
the status didn't change."""
the status didn't change.
"""
status_change = chat_member_update.difference().get("status")
old_is_member, new_is_member = chat_member_update.difference().get("is_member", (None, None))

Expand Down
9 changes: 9 additions & 0 deletions examples/conversationbot.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@


def start(update: Update, _: CallbackContext) -> int:
"""Starts the conversation and asks the user about their gender."""
reply_keyboard = [['Boy', 'Girl', 'Other']]

update.message.reply_text(
Expand All @@ -50,6 +51,7 @@ def start(update: Update, _: CallbackContext) -> int:


def gender(update: Update, _: CallbackContext) -> int:
"""Stores the selected gender and asks for a photo."""
user = update.message.from_user
logger.info("Gender of %s: %s", user.first_name, update.message.text)
update.message.reply_text(
Expand All @@ -62,6 +64,7 @@ def gender(update: Update, _: CallbackContext) -> int:


def photo(update: Update, _: CallbackContext) -> int:
"""Stores the photo and asks for a location."""
user = update.message.from_user
photo_file = update.message.photo[-1].get_file()
photo_file.download('user_photo.jpg')
Expand All @@ -74,6 +77,7 @@ def photo(update: Update, _: CallbackContext) -> int:


def skip_photo(update: Update, _: CallbackContext) -> int:
"""Skips the photo and asks for a location."""
user = update.message.from_user
logger.info("User %s did not send a photo.", user.first_name)
update.message.reply_text(
Expand All @@ -84,6 +88,7 @@ def skip_photo(update: Update, _: CallbackContext) -> int:


def location(update: Update, _: CallbackContext) -> int:
"""Stores the location and asks for some info about the user."""
user = update.message.from_user
user_location = update.message.location
logger.info(
Expand All @@ -97,6 +102,7 @@ def location(update: Update, _: CallbackContext) -> int:


def skip_location(update: Update, _: CallbackContext) -> int:
"""Skips the location and asks for info about the user."""
user = update.message.from_user
logger.info("User %s did not send a location.", user.first_name)
update.message.reply_text(
Expand All @@ -107,6 +113,7 @@ def skip_location(update: Update, _: CallbackContext) -> int:


def bio(update: Update, _: CallbackContext) -> int:
"""Stores the info about the user and ends the conversation."""
user = update.message.from_user
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.')
Expand All @@ -115,6 +122,7 @@ def bio(update: Update, _: CallbackContext) -> int:


def cancel(update: Update, _: CallbackContext) -> int:
"""Cancels and ends the conversation."""
user = update.message.from_user
logger.info("User %s canceled the conversation.", user.first_name)
update.message.reply_text(
Expand All @@ -125,6 +133,7 @@ def cancel(update: Update, _: CallbackContext) -> int:


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

Expand Down
13 changes: 8 additions & 5 deletions examples/conversationbot2.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,15 +45,13 @@


def facts_to_str(user_data: Dict[str, str]) -> str:
facts = list()

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

"""Helper function for formatting the gathered user info."""
facts = [f'{key} - {value}' for key, value in user_data.items()]
return "\n".join(facts).join(['\n', '\n'])


def start(update: Update, _: CallbackContext) -> int:
"""Start the conversation and ask user for input."""
update.message.reply_text(
"Hi! My name is Doctor Botter. I will hold a more complex conversation with you. "
"Why don't you tell me something about yourself?",
Expand All @@ -64,6 +62,7 @@ def start(update: Update, _: CallbackContext) -> int:


def regular_choice(update: Update, context: CallbackContext) -> int:
"""Ask the user for info about the selected predefined choice."""
text = update.message.text
context.user_data['choice'] = text
update.message.reply_text(f'Your {text.lower()}? Yes, I would love to hear about that!')
Expand All @@ -72,6 +71,7 @@ def regular_choice(update: Update, context: CallbackContext) -> int:


def custom_choice(update: Update, _: CallbackContext) -> int:
"""Ask the user for a description of a custom category."""
update.message.reply_text(
'Alright, please send me the category first, for example "Most impressive skill"'
)
Expand All @@ -80,6 +80,7 @@ def custom_choice(update: Update, _: CallbackContext) -> int:


def received_information(update: Update, context: CallbackContext) -> int:
"""Store info provided by user and ask for the next category."""
user_data = context.user_data
text = update.message.text
category = user_data['choice']
Expand All @@ -97,6 +98,7 @@ def received_information(update: Update, context: CallbackContext) -> int:


def done(update: Update, context: CallbackContext) -> int:
"""Display the gathered info and end the conversation."""
user_data = context.user_data
if 'choice' in user_data:
del user_data['choice']
Expand All @@ -111,6 +113,7 @@ def done(update: Update, context: CallbackContext) -> int:


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

Expand Down
6 changes: 3 additions & 3 deletions examples/errorhandlerbot.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@
# pylint: disable=C0116
# This program is dedicated to the public domain under the CC0 license.

"""
This is a very simple example on how one could implement a custom error handler
"""
"""This is a very simple example on how one could implement a custom error handler."""
import html
import json
import logging
Expand Down Expand Up @@ -59,13 +57,15 @@ def bad_command(_: Update, context: CallbackContext) -> None:


def start(update: Update, _: CallbackContext) -> None:
"""Displays info on how to trigger an error."""
update.effective_message.reply_html(
'Use /bad_command to cause an error.\n'
f'Your chat id is <code>{update.effective_chat.id}</code>.'
)


def main() -> None:
"""Run the bot."""
# Create the Updater and pass it your bot's token.
updater = Updater(BOT_TOKEN)

Expand Down
1 change: 1 addition & 0 deletions examples/inlinebot.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ def inlinequery(update: Update, _: CallbackContext) -> None:


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

Expand Down
4 changes: 4 additions & 0 deletions examples/inlinekeyboard.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@


def start(update: Update, _: CallbackContext) -> None:
"""Sends a message with three inline buttons attached."""
keyboard = [
[
InlineKeyboardButton("Option 1", callback_data='1'),
Expand All @@ -32,6 +33,7 @@ def start(update: Update, _: CallbackContext) -> None:


def button(update: Update, _: CallbackContext) -> None:
"""Parses the CallbackQuery and updates the message text."""
query = update.callback_query

# CallbackQueries need to be answered, even if no notification to the user is needed
Expand All @@ -42,10 +44,12 @@ def button(update: Update, _: CallbackContext) -> None:


def help_command(update: Update, _: CallbackContext) -> None:
"""Displays info on how to use the bot."""
update.message.reply_text("Use /start to test this bot.")


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

Expand Down
4 changes: 3 additions & 1 deletion examples/inlinekeyboard2.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,14 +151,16 @@ def four(update: Update, _: CallbackContext) -> int:

def end(update: Update, _: CallbackContext) -> int:
"""Returns `ConversationHandler.END`, which tells the
ConversationHandler that the conversation is over"""
ConversationHandler that the conversation is over.
"""
query = update.callback_query
query.answer()
query.edit_message_text(text="See you next time!")
return ConversationHandler.END


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

Expand Down
1 change: 1 addition & 0 deletions examples/nestedconversationbot.py
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,7 @@ def stop_nested(update: Update, _: CallbackContext) -> str:


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

Expand Down
18 changes: 11 additions & 7 deletions examples/paymentbot.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@
# pylint: disable=C0116
# This program is dedicated to the public domain under the CC0 license.

"""
Basic example for a bot that can receive payment from user.
"""
"""Basic example for a bot that can receive payment from user."""

import logging

Expand All @@ -28,6 +26,7 @@


def start_callback(update: Update, _: CallbackContext) -> None:
"""Displays info on how to use the bot."""
msg = (
"Use /shipping to get an invoice for shipping-payment, or /noshipping for an "
"invoice without shipping."
Expand All @@ -37,6 +36,7 @@ def start_callback(update: Update, _: CallbackContext) -> None:


def start_with_shipping_callback(update: Update, context: CallbackContext) -> None:
"""Sends an invoice with shipping-payment."""
chat_id = update.message.chat_id
title = "Payment Example"
description = "Payment Example using python-telegram-bot"
Expand Down Expand Up @@ -70,6 +70,7 @@ def start_with_shipping_callback(update: Update, context: CallbackContext) -> No


def start_without_shipping_callback(update: Update, context: CallbackContext) -> None:
"""Sends an invoice without shipping-payment."""
chat_id = update.message.chat_id
title = "Payment Example"
description = "Payment Example using python-telegram-bot"
Expand All @@ -91,24 +92,25 @@ def start_without_shipping_callback(update: Update, context: CallbackContext) ->


def shipping_callback(update: Update, _: CallbackContext) -> None:
"""Answers the ShippingQuery with ShippingOptions"""
query = update.shipping_query
# check the payload, is this from your bot?
if query.invoice_payload != 'Custom-Payload':
# answer False pre_checkout_query
query.answer(ok=False, error_message="Something went wrong...")
return

options = list()
# a single LabeledPrice
options.append(ShippingOption('1', 'Shipping Option A', [LabeledPrice('A', 100)]))
# an array of LabeledPrice objects
# First option has a single LabeledPrice
options = [ShippingOption('1', 'Shipping Option A', [LabeledPrice('A', 100)])]
# second option has an array of LabeledPrice objects
price_list = [LabeledPrice('B1', 150), LabeledPrice('B2', 200)]
options.append(ShippingOption('2', 'Shipping Option B', price_list))
query.answer(ok=True, shipping_options=options)


# after (optional) shipping, it's the pre-checkout
def precheckout_callback(update: Update, _: CallbackContext) -> None:
"""Answers the PreQecheckoutQuery"""
query = update.pre_checkout_query
# check the payload, is this from your bot?
if query.invoice_payload != 'Custom-Payload':
Expand All @@ -120,11 +122,13 @@ def precheckout_callback(update: Update, _: CallbackContext) -> None:

# finally, after contacting the payment provider...
def successful_payment_callback(update: Update, _: CallbackContext) -> None:
"""Confirms the successful payment."""
# do something after successfully receiving payment?
update.message.reply_text("Thank you for your payment!")


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

Expand Down
20 changes: 11 additions & 9 deletions examples/persistentconversationbot.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@
CallbackContext,
)


# Enable logging
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO
Expand All @@ -47,15 +46,13 @@


def facts_to_str(user_data: Dict[str, str]) -> str:
facts = []

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

"""Helper function for formatting the gathered user info."""
facts = [f'{key} - {value}' for key, value in user_data.items()]
return "\n".join(facts).join(['\n', '\n'])


def start(update: Update, context: CallbackContext) -> int:
"""Start the conversation, display any stored data and ask user for input."""
reply_text = "Hi! My name is Doctor Botter."
if context.user_data:
reply_text += (
Expand All @@ -73,6 +70,7 @@ def start(update: Update, context: CallbackContext) -> int:


def regular_choice(update: Update, context: CallbackContext) -> int:
"""Ask the user for info about the selected predefined choice."""
text = update.message.text.lower()
context.user_data['choice'] = text
if context.user_data.get(text):
Expand All @@ -87,6 +85,7 @@ def regular_choice(update: Update, context: CallbackContext) -> int:


def custom_choice(update: Update, _: CallbackContext) -> int:
"""Ask the user for a description of a custom category."""
update.message.reply_text(
'Alright, please send me the category first, for example "Most impressive skill"'
)
Expand All @@ -95,6 +94,7 @@ def custom_choice(update: Update, _: CallbackContext) -> int:


def received_information(update: Update, context: CallbackContext) -> int:
"""Store info provided by user and ask for the next category."""
text = update.message.text
category = context.user_data['choice']
context.user_data[category] = text.lower()
Expand All @@ -103,32 +103,34 @@ def received_information(update: Update, context: CallbackContext) -> int:
update.message.reply_text(
"Neat! Just so you know, this is what you already told me:"
f"{facts_to_str(context.user_data)}"
"You can tell me more, or change your opinion on "
"something.",
"You can tell me more, or change your opinion on something.",
reply_markup=markup,
)

return CHOOSING


def show_data(update: Update, context: CallbackContext) -> None:
"""Display the gathered info."""
update.message.reply_text(
f"This is what you already told me: {facts_to_str(context.user_data)}"
)


def done(update: Update, context: CallbackContext) -> int:
"""Display the gathered info and end the conversation."""
if 'choice' in context.user_data:
del context.user_data['choice']

update.message.reply_text(
"I learned these facts about you:" f"{facts_to_str(context.user_data)}Until next time!",
f"I learned these facts about you: {facts_to_str(context.user_data)}Until next time!",
reply_markup=ReplyKeyboardRemove(),
)
return ConversationHandler.END


def main() -> None:
"""Run the bot."""
# Create the Updater and pass it your bot's token.
persistence = PicklePersistence(filename='conversationbot')
updater = Updater("TOKEN", persistence=persistence)
Expand Down
Loading