Skip to content

Commit

Permalink
code cleanuop & renamed aio -> asyncio
Browse files Browse the repository at this point in the history
  • Loading branch information
coder2020official committed Jul 27, 2024
1 parent 3fec98c commit dbfa514
Show file tree
Hide file tree
Showing 5 changed files with 136 additions and 53 deletions.
98 changes: 70 additions & 28 deletions examples/asynchronous_telebot/custom_states.py
Original file line number Diff line number Diff line change
@@ -1,39 +1,53 @@
from telebot import async_telebot
from telebot import asyncio_filters, types
from telebot.states import State, StatesGroup
from telebot.states.aio.context import StateContext
from telebot import async_telebot, asyncio_filters, types
from telebot.asyncio_storage import StateMemoryStorage
from telebot.states import State, StatesGroup
from telebot.states.asyncio.context import StateContext

# Initialize the bot
state_storage = StateMemoryStorage() # don't use this in production; switch to redis
bot = async_telebot.AsyncTeleBot("TOKEN", state_storage=state_storage)


# Define states
class MyStates(StatesGroup):
name = State()
age = State()
color = State()
hobby = State()


# Start command handler
@bot.message_handler(commands=['start'])
@bot.message_handler(commands=["start"])
async def start_ex(message: types.Message, state: StateContext):
await state.set(MyStates.name)
await bot.send_message(message.chat.id, 'Hello! What is your first name?', reply_to_message_id=message.message_id)
await bot.send_message(
message.chat.id,
"Hello! What is your first name?",
reply_to_message_id=message.message_id,
)


# Cancel command handler
@bot.message_handler(state="*", commands=['cancel'])
@bot.message_handler(state="*", commands=["cancel"])
async def any_state(message: types.Message, state: StateContext):
await state.delete()
await bot.send_message(message.chat.id, 'Your information has been cleared. Type /start to begin again.', reply_to_message_id=message.message_id)
await bot.send_message(
message.chat.id,
"Your information has been cleared. Type /start to begin again.",
reply_to_message_id=message.message_id,
)


# Handler for name input
@bot.message_handler(state=MyStates.name)
async def name_get(message: types.Message, state: StateContext):
await state.set(MyStates.age)
await bot.send_message(message.chat.id, "How old are you?", reply_to_message_id=message.message_id)
await bot.send_message(
message.chat.id, "How old are you?", reply_to_message_id=message.message_id
)
await state.add_data(name=message.text)


# Handler for age input
@bot.message_handler(state=MyStates.age, is_digit=True)
async def ask_color(message: types.Message, state: StateContext):
Expand All @@ -46,7 +60,13 @@ async def ask_color(message: types.Message, state: StateContext):
buttons = [types.KeyboardButton(color) for color in colors]
keyboard.add(*buttons)

await bot.send_message(message.chat.id, "What is your favorite color? Choose from the options below.", reply_markup=keyboard, reply_to_message_id=message.message_id)
await bot.send_message(
message.chat.id,
"What is your favorite color? Choose from the options below.",
reply_markup=keyboard,
reply_to_message_id=message.message_id,
)


# Handler for color input
@bot.message_handler(state=MyStates.color)
Expand All @@ -60,15 +80,23 @@ async def ask_hobby(message: types.Message, state: StateContext):
buttons = [types.KeyboardButton(hobby) for hobby in hobbies]
keyboard.add(*buttons)

await bot.send_message(message.chat.id, "What is one of your hobbies? Choose from the options below.", reply_markup=keyboard, reply_to_message_id=message.message_id)
await bot.send_message(
message.chat.id,
"What is one of your hobbies? Choose from the options below.",
reply_markup=keyboard,
reply_to_message_id=message.message_id,
)


# Handler for hobby input; use filters to ease validation
@bot.message_handler(state=MyStates.hobby, text=['Reading', 'Traveling', 'Gaming', 'Cooking'])
@bot.message_handler(
state=MyStates.hobby, text=["Reading", "Traveling", "Gaming", "Cooking"]
)
async def finish(message: types.Message, state: StateContext):
async with state.data() as data:
name = data.get('name')
age = data.get('age')
color = data.get('color')
name = data.get("name")
age = data.get("age")
color = data.get("color")
hobby = message.text # Get the hobby from the message text

# Provide a fun fact based on color
Expand All @@ -79,34 +107,48 @@ async def finish(message: types.Message, state: StateContext):
"Yellow": "Yellow is a cheerful color often associated with happiness.",
"Purple": "Purple signifies royalty and luxury.",
"Orange": "Orange is a vibrant color that stimulates enthusiasm.",
"Other": "Colors have various meanings depending on context."
"Other": "Colors have various meanings depending on context.",
}
color_fact = color_facts.get(color, "Colors have diverse meanings, and yours is unique!")

msg = (f"Thank you for sharing! Here is a summary of your information:\n"
f"First Name: {name}\n"
f"Age: {age}\n"
f"Favorite Color: {color}\n"
f"Fun Fact about your color: {color_fact}\n"
f"Favorite Hobby: {hobby}")

await bot.send_message(message.chat.id, msg, parse_mode="html", reply_to_message_id=message.message_id)
color_fact = color_facts.get(
color, "Colors have diverse meanings, and yours is unique!"
)

msg = (
f"Thank you for sharing! Here is a summary of your information:\n"
f"First Name: {name}\n"
f"Age: {age}\n"
f"Favorite Color: {color}\n"
f"Fun Fact about your color: {color_fact}\n"
f"Favorite Hobby: {hobby}"
)

await bot.send_message(
message.chat.id, msg, parse_mode="html", reply_to_message_id=message.message_id
)
await state.delete()


# Handler for incorrect age input
@bot.message_handler(state=MyStates.age, is_digit=False)
async def age_incorrect(message: types.Message):
await bot.send_message(message.chat.id, 'Please enter a valid number for age.', reply_to_message_id=message.message_id)
await bot.send_message(
message.chat.id,
"Please enter a valid number for age.",
reply_to_message_id=message.message_id,
)


# Add custom filters
bot.add_custom_filter(asyncio_filters.StateFilter(bot))
bot.add_custom_filter(asyncio_filters.IsDigitFilter())
bot.add_custom_filter(asyncio_filters.TextMatchFilter())

# necessary for state parameter in handlers.
from telebot.states.aio.middleware import StateMiddleware
from telebot.states.asyncio.middleware import StateMiddleware

bot.setup_middleware(StateMiddleware(bot))

# Start polling
import asyncio

asyncio.run(bot.polling())
91 changes: 66 additions & 25 deletions examples/custom_states.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@

# Initialize the bot
state_storage = StateMemoryStorage() # don't use this in production; switch to redis
bot = telebot.TeleBot("TOKEN", state_storage=state_storage,
use_class_middlewares=True)
bot = telebot.TeleBot("TOKEN", state_storage=state_storage, use_class_middlewares=True)


# Define states
class MyStates(StatesGroup):
Expand All @@ -16,25 +16,39 @@ class MyStates(StatesGroup):
color = State()
hobby = State()


# Start command handler
@bot.message_handler(commands=['start'])
@bot.message_handler(commands=["start"])
def start_ex(message: types.Message, state: StateContext):
state.set(MyStates.name)
bot.send_message(message.chat.id, 'Hello! What is your first name?', reply_to_message_id=message.message_id)
bot.send_message(
message.chat.id,
"Hello! What is your first name?",
reply_to_message_id=message.message_id,
)


# Cancel command handler
@bot.message_handler(state="*", commands=['cancel'])
@bot.message_handler(state="*", commands=["cancel"])
def any_state(message: types.Message, state: StateContext):
state.delete()
bot.send_message(message.chat.id, 'Your information has been cleared. Type /start to begin again.', reply_to_message_id=message.message_id)
bot.send_message(
message.chat.id,
"Your information has been cleared. Type /start to begin again.",
reply_to_message_id=message.message_id,
)


# Handler for name input
@bot.message_handler(state=MyStates.name)
def name_get(message: types.Message, state: StateContext):
state.set(MyStates.age)
bot.send_message(message.chat.id, "How old are you?", reply_to_message_id=message.message_id)
bot.send_message(
message.chat.id, "How old are you?", reply_to_message_id=message.message_id
)
state.add_data(name=message.text)


# Handler for age input
@bot.message_handler(state=MyStates.age, is_digit=True)
def ask_color(message: types.Message, state: StateContext):
Expand All @@ -47,7 +61,13 @@ def ask_color(message: types.Message, state: StateContext):
buttons = [types.KeyboardButton(color) for color in colors]
keyboard.add(*buttons)

bot.send_message(message.chat.id, "What is your favorite color? Choose from the options below.", reply_markup=keyboard, reply_to_message_id=message.message_id)
bot.send_message(
message.chat.id,
"What is your favorite color? Choose from the options below.",
reply_markup=keyboard,
reply_to_message_id=message.message_id,
)


# Handler for color input
@bot.message_handler(state=MyStates.color)
Expand All @@ -61,15 +81,23 @@ def ask_hobby(message: types.Message, state: StateContext):
buttons = [types.KeyboardButton(hobby) for hobby in hobbies]
keyboard.add(*buttons)

bot.send_message(message.chat.id, "What is one of your hobbies? Choose from the options below.", reply_markup=keyboard, reply_to_message_id=message.message_id)
bot.send_message(
message.chat.id,
"What is one of your hobbies? Choose from the options below.",
reply_markup=keyboard,
reply_to_message_id=message.message_id,
)


# Handler for hobby input
@bot.message_handler(state=MyStates.hobby, text=['Reading', 'Traveling', 'Gaming', 'Cooking'])
@bot.message_handler(
state=MyStates.hobby, text=["Reading", "Traveling", "Gaming", "Cooking"]
)
def finish(message: types.Message, state: StateContext):
with state.data() as data:
name = data.get('name')
age = data.get('age')
color = data.get('color')
name = data.get("name")
age = data.get("age")
color = data.get("color")
hobby = message.text # Get the hobby from the message text

# Provide a fun fact based on color
Expand All @@ -80,24 +108,36 @@ def finish(message: types.Message, state: StateContext):
"Yellow": "Yellow is a cheerful color often associated with happiness.",
"Purple": "Purple signifies royalty and luxury.",
"Orange": "Orange is a vibrant color that stimulates enthusiasm.",
"Other": "Colors have various meanings depending on context."
"Other": "Colors have various meanings depending on context.",
}
color_fact = color_facts.get(color, "Colors have diverse meanings, and yours is unique!")

msg = (f"Thank you for sharing! Here is a summary of your information:\n"
f"First Name: {name}\n"
f"Age: {age}\n"
f"Favorite Color: {color}\n"
f"Fun Fact about your color: {color_fact}\n"
f"Favorite Hobby: {hobby}")

bot.send_message(message.chat.id, msg, parse_mode="html", reply_to_message_id=message.message_id)
color_fact = color_facts.get(
color, "Colors have diverse meanings, and yours is unique!"
)

msg = (
f"Thank you for sharing! Here is a summary of your information:\n"
f"First Name: {name}\n"
f"Age: {age}\n"
f"Favorite Color: {color}\n"
f"Fun Fact about your color: {color_fact}\n"
f"Favorite Hobby: {hobby}"
)

bot.send_message(
message.chat.id, msg, parse_mode="html", reply_to_message_id=message.message_id
)
state.delete()


# Handler for incorrect age input
@bot.message_handler(state=MyStates.age, is_digit=False)
def age_incorrect(message: types.Message):
bot.send_message(message.chat.id, 'Please enter a valid number for age.', reply_to_message_id=message.message_id)
bot.send_message(
message.chat.id,
"Please enter a valid number for age.",
reply_to_message_id=message.message_id,
)


# Add custom filters
bot.add_custom_filter(custom_filters.StateFilter(bot))
Expand All @@ -106,6 +146,7 @@ def age_incorrect(message: types.Message):

# necessary for state parameter in handlers.
from telebot.states.sync.middleware import StateMiddleware

bot.setup_middleware(StateMiddleware(bot))

# Start polling
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.

0 comments on commit dbfa514

Please sign in to comment.