mirror of
https://github.com/aiogram/aiogram.git
synced 2025-12-09 01:15:31 +00:00
Minor typos fixes in examples
This commit is contained in:
parent
e1f61fd4ae
commit
f9c44bb2d7
7 changed files with 52 additions and 51 deletions
|
|
@ -27,7 +27,7 @@ async def demo_filter(message: types.Message):
|
|||
@dp.message_handler(demo_filter)
|
||||
async def send_welcome(message: types.Message):
|
||||
# Get data from context
|
||||
# All of that available only in current context and from current update object
|
||||
# All of this is available only in current context and from current update object
|
||||
# `data`- pseudo-alias for `ctx.get_update().conf['_context_data']`
|
||||
command = data['command']
|
||||
args = data['args']
|
||||
|
|
|
|||
|
|
@ -26,30 +26,30 @@ GENDER = 'process_gender'
|
|||
@dp.message_handler(commands=['start'])
|
||||
async def cmd_start(message: types.Message):
|
||||
"""
|
||||
Entry point to conversation
|
||||
Conversation's entry point
|
||||
"""
|
||||
# Get current state
|
||||
state = dp.current_state(chat=message.chat.id, user=message.from_user.id)
|
||||
# Update user state
|
||||
# Update user's state
|
||||
await state.set_state(NAME)
|
||||
|
||||
await message.reply("Hi there! What's your name?")
|
||||
|
||||
|
||||
# You can use state '*' if you need to handle all states.
|
||||
# You can use state '*' if you need to handle all states
|
||||
@dp.message_handler(state='*', commands=['cancel'])
|
||||
@dp.message_handler(state='*', func=lambda message: message.text.lower() == 'cancel')
|
||||
async def cancel_handler(message: types.Message):
|
||||
"""
|
||||
Allow to cancel any action
|
||||
Allow user to cancel any action
|
||||
"""
|
||||
with dp.current_state(chat=message.chat.id, user=message.from_user.id) as state:
|
||||
# Ignore command if user is not in any (defined) state
|
||||
if await state.get_state() is None:
|
||||
return
|
||||
|
||||
# Otherwise cancel state and inform user about that.
|
||||
# And just in case remove keyboard.
|
||||
# Otherwise cancel state and inform user about it
|
||||
# And remove keyboard (just in case)
|
||||
await state.reset_state(with_data=True)
|
||||
await message.reply('Canceled.', reply_markup=types.ReplyKeyboardRemove())
|
||||
|
||||
|
|
@ -68,13 +68,13 @@ async def process_name(message: types.Message):
|
|||
await message.reply("How old are you?")
|
||||
|
||||
|
||||
# Check age. Age must be is digit
|
||||
# Check age. Age gotta be digit
|
||||
@dp.message_handler(state=AGE, func=lambda message: not message.text.isdigit())
|
||||
async def failed_process_age(message: types.Message):
|
||||
"""
|
||||
If age is in invalid format
|
||||
If age is invalid
|
||||
"""
|
||||
return await message.reply("Age should be a number.\nHow old are you?")
|
||||
return await message.reply("Age gotta be a number.\nHow old are you? (digits only)")
|
||||
|
||||
|
||||
@dp.message_handler(state=AGE, func=lambda message: message.text.isdigit())
|
||||
|
|
@ -93,19 +93,19 @@ async def process_age(message: types.Message):
|
|||
|
||||
|
||||
@dp.message_handler(state=GENDER, func=lambda message: message.text not in ["Male", "Female", "Other"])
|
||||
async def failed_process_sex(message: types.Message):
|
||||
async def failed_process_gender(message: types.Message):
|
||||
"""
|
||||
Sex must be always (in this example) is one of: Male, Female, Other.
|
||||
In this example gender has to be one of: Male, Female, Other.
|
||||
"""
|
||||
return await message.reply("Bad gender name. Choose you gender from keyboard.")
|
||||
|
||||
|
||||
@dp.message_handler(state=GENDER)
|
||||
async def process_sex(message: types.Message):
|
||||
async def process_gender(message: types.Message):
|
||||
state = dp.current_state(chat=message.chat.id, user=message.from_user.id)
|
||||
|
||||
data = await state.get_data()
|
||||
data['sex'] = message.text
|
||||
data['gender'] = message.text
|
||||
|
||||
# Remove keyboard
|
||||
markup = types.ReplyKeyboardRemove()
|
||||
|
|
@ -114,7 +114,7 @@ async def process_sex(message: types.Message):
|
|||
await bot.send_message(message.chat.id, text(
|
||||
text('Hi! Nice to meet you,', bold(data['name'])),
|
||||
text('Age:', data['age']),
|
||||
text('Sex:', data['sex']),
|
||||
text('Gender:', data['gender']),
|
||||
sep='\n'), reply_markup=markup, parse_mode=ParseMode.MARKDOWN)
|
||||
|
||||
# Finish conversation
|
||||
|
|
|
|||
|
|
@ -39,7 +39,8 @@ async def send_welcome(message: types.Message):
|
|||
# media.attach_photo('<file_id>', 'cat-cat-cat.')
|
||||
|
||||
# Done! Send media group
|
||||
await bot.send_media_group(message.chat.id, media=media, reply_to_message_id=message.message_id)
|
||||
await bot.send_media_group(message.chat.id, media=media,
|
||||
reply_to_message_id=message.message_id)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ TOKEN = 'BOT TOKEN HERE'
|
|||
|
||||
loop = asyncio.get_event_loop()
|
||||
|
||||
# In this example used Redis storage
|
||||
# In this example Redis storage is used
|
||||
storage = RedisStorage2(db=5)
|
||||
|
||||
bot = Bot(token=TOKEN, loop=loop)
|
||||
|
|
@ -48,7 +48,7 @@ class ThrottlingMiddleware(BaseMiddleware):
|
|||
|
||||
async def on_process_message(self, message: types.Message):
|
||||
"""
|
||||
That handler will be called when dispatcher receive message
|
||||
This handler is called when dispatcher receives a message
|
||||
|
||||
:param message:
|
||||
"""
|
||||
|
|
@ -58,7 +58,7 @@ class ThrottlingMiddleware(BaseMiddleware):
|
|||
# Get dispatcher from context
|
||||
dispatcher = ctx.get_dispatcher()
|
||||
|
||||
# If handler was configured get rate limit and key from handler
|
||||
# If handler was configured, get rate limit and key from handler
|
||||
if handler:
|
||||
limit = getattr(handler, 'throttling_rate_limit', self.rate_limit)
|
||||
key = getattr(handler, 'throttling_key', f"{self.prefix}_{handler.__name__}")
|
||||
|
|
@ -90,7 +90,7 @@ class ThrottlingMiddleware(BaseMiddleware):
|
|||
else:
|
||||
key = f"{self.prefix}_message"
|
||||
|
||||
# Calculate how many time left to the end of block.
|
||||
# Calculate how many time is left till the block ends
|
||||
delta = throttled.rate - throttled.delta
|
||||
|
||||
# Prevent flooding
|
||||
|
|
@ -109,10 +109,10 @@ class ThrottlingMiddleware(BaseMiddleware):
|
|||
|
||||
|
||||
@dp.message_handler(commands=['start'])
|
||||
@rate_limit(5, 'start') # is not required but with that you can configure throttling manager for current handler
|
||||
@rate_limit(5, 'start') # this is not required but you can configure throttling manager for current handler using it
|
||||
async def cmd_test(message: types.Message):
|
||||
# You can use that command every 5 seconds
|
||||
await message.reply('Test passed! You can use that command every 5 seconds.')
|
||||
# You can use this command every 5 seconds
|
||||
await message.reply('Test passed! You can use this command every 5 seconds.')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
|
|
|||
|
|
@ -12,9 +12,9 @@ from aiogram.utils.markdown import bold, code, italic, text
|
|||
API_TOKEN = 'BOT TOKEN HERE'
|
||||
PROXY_URL = 'http://PROXY_URL'
|
||||
|
||||
# If authentication is required in your proxy then uncomment next line and change login/password for that
|
||||
# If authentication is required in your proxy then uncomment next line and change login/password for it
|
||||
# PROXY_AUTH = aiohttp.BasicAuth(login='login', password='password')
|
||||
# And add `proxy_auth=PROXY_AUTH` argument in line 25, like that:
|
||||
# And add `proxy_auth=PROXY_AUTH` argument in line 25, like this:
|
||||
# >>> bot = Bot(token=API_TOKEN, loop=loop, proxy=PROXY_URL, proxy_auth=PROXY_AUTH)
|
||||
|
||||
# Get my ip URL
|
||||
|
|
@ -29,7 +29,7 @@ dp = Dispatcher(bot)
|
|||
|
||||
@dp.message_handler(commands=['start'])
|
||||
async def cmd_start(message: types.Message):
|
||||
# Create temporary session
|
||||
# Create a temporary session
|
||||
session = bot.create_temp_session()
|
||||
|
||||
content = []
|
||||
|
|
@ -39,7 +39,7 @@ async def cmd_start(message: types.Message):
|
|||
content.append(text(':globe_showing_Americas:', bold('IP:'), code(await response.text())))
|
||||
# This line is formatted to '🌎 *IP:* `YOUR IP`'
|
||||
|
||||
# Make request with proxy
|
||||
# Make request through proxy
|
||||
async with session.get(GET_IP_URL, proxy=bot.proxy, proxy_auth=bot.proxy_auth) as response:
|
||||
content.append(text(':locked_with_key:', bold('IP:'), code(await response.text()), italic('via proxy')))
|
||||
# This line is formatted to '🔐 *IP:* `YOUR IP` _via proxy_'
|
||||
|
|
@ -51,11 +51,11 @@ async def cmd_start(message: types.Message):
|
|||
bot.destroy_temp_session(session)
|
||||
|
||||
# In this example you can see emoji codes: ":globe_showing_Americas:" and ":locked_with_key:"
|
||||
# Full emoji cheat sheet you can found at https://www.webpagefx.com/tools/emoji-cheat-sheet/
|
||||
# For representing emoji codes to real emoji use emoji util (aiogram.utils.emoji)
|
||||
# and you need to be installed emoji module
|
||||
# You can find full emoji cheat sheet at https://www.webpagefx.com/tools/emoji-cheat-sheet/
|
||||
# For representing emoji codes into real emoji use emoji util (aiogram.utils.emoji)
|
||||
# (you have to install emoji module)
|
||||
|
||||
# For example emojize('Moon face :new_moon_face:') is represents to 'Moon face 🌚'
|
||||
# For example emojize('Moon face :new_moon_face:') is transformed to 'Moon face 🌚'
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
|
|
|||
|
|
@ -20,8 +20,8 @@ logging.basicConfig(level=logging.INFO)
|
|||
loop = asyncio.get_event_loop()
|
||||
bot = Bot(token=API_TOKEN, loop=loop)
|
||||
|
||||
# Throttling manager does not working without Leaky Bucket.
|
||||
# Then need to use storage's. For example use simple in-memory storage.
|
||||
# Throttling manager does not work without Leaky Bucket.
|
||||
# Then need to use storages. For example use simple in-memory storage.
|
||||
storage = MemoryStorage()
|
||||
dp = Dispatcher(bot, storage=storage)
|
||||
|
||||
|
|
@ -29,13 +29,13 @@ dp = Dispatcher(bot, storage=storage)
|
|||
@dp.message_handler(commands=['start', 'help'])
|
||||
async def send_welcome(message: types.Message):
|
||||
try:
|
||||
# Execute throttling manager with rate-limit equals to 2 seconds for key "start"
|
||||
# Execute throttling manager with rate-limit equal to 2 seconds for key "start"
|
||||
await dp.throttle('start', rate=2)
|
||||
except Throttled:
|
||||
# If request is throttled the `Throttled` exception will be raised.
|
||||
# If request is throttled, the `Throttled` exception will be raised
|
||||
await message.reply('Too many requests!')
|
||||
else:
|
||||
# Otherwise do something.
|
||||
# Otherwise do something
|
||||
await message.reply("Hi!\nI'm EchoBot!\nPowered by aiogram.")
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -34,19 +34,19 @@ dp = Dispatcher(bot, storage=storage)
|
|||
|
||||
|
||||
async def cmd_start(message: types.Message):
|
||||
# Yep. aiogram allow to send response over webhook.
|
||||
# Yep. aiogram allows to respond into webhook.
|
||||
# https://core.telegram.org/bots/api#making-requests-when-getting-updates
|
||||
return SendMessage(chat_id=message.chat.id, text='Hi from webhook!',
|
||||
reply_to_message_id=message.message_id)
|
||||
|
||||
|
||||
async def cmd_about(message: types.Message):
|
||||
# In this function used markdown utils for formatting message text
|
||||
# In this function markdown utils are userd for formatting message text
|
||||
return SendMessage(message.chat.id, text(
|
||||
bold('Hi! I\'m simple telegram bot.'),
|
||||
bold('Hi! I\'m just a simple telegram bot.'),
|
||||
'',
|
||||
text('I\'m worked on', bold('Python', Version(*sys.version_info[:]))),
|
||||
text('With', link(text('aiogram', aiogram.VERSION), 'https://bitbucket.org/illemius/aiogram')),
|
||||
text('I\'m powered by', bold('Python', Version(*sys.version_info[:]))),
|
||||
text('With', link(text('aiogram', aiogram.VERSION), 'https://github.com/aiogram/aiogram')),
|
||||
sep='\n'
|
||||
), parse_mode=ParseMode.MARKDOWN)
|
||||
|
||||
|
|
@ -55,7 +55,7 @@ async def cancel(message: types.Message):
|
|||
# Get current state context
|
||||
state = dp.current_state(chat=message.chat.id, user=message.from_user.id)
|
||||
|
||||
# If now user in any state - cancel it.
|
||||
# If current user in any state - cancel it.
|
||||
if await state.get_state() is not None:
|
||||
await state.set_state(state=None)
|
||||
return SendMessage(message.chat.id, 'Current action is canceled.')
|
||||
|
|
@ -66,7 +66,7 @@ async def unknown(message: types.Message):
|
|||
"""
|
||||
Handler for unknown messages.
|
||||
"""
|
||||
return SendMessage(message.chat.id, 'I don\'t know what to do with that content type. Sorry :c')
|
||||
return SendMessage(message.chat.id, f"I don\'t know what to do with content type `{message.content_type()}`. Sorry :c")
|
||||
|
||||
|
||||
async def cmd_id(message: types.Message):
|
||||
|
|
@ -103,16 +103,16 @@ async def cmd_id(message: types.Message):
|
|||
|
||||
|
||||
async def on_startup(app):
|
||||
# Demonstrate one of available method of registering handlers
|
||||
# Demonstrate one of the available methods for registering handlers
|
||||
# This command available only in main state (state=None)
|
||||
dp.register_message_handler(cmd_start, commands=['start'])
|
||||
|
||||
# This handler available in all states in any time.
|
||||
# This handler is available in all states at any time.
|
||||
dp.register_message_handler(cmd_about, commands=['help', 'about'], state='*')
|
||||
dp.register_message_handler(unknown, content_types=BAD_CONTENT,
|
||||
func=lambda message: message.chat.type == ChatType.PRIVATE)
|
||||
|
||||
# You can register one handler with multiple filters set
|
||||
# You are able to register one function handler for multiple conditions
|
||||
dp.register_message_handler(cancel, commands=['cancel'], state='*')
|
||||
dp.register_message_handler(cancel, func=lambda message: message.text.lower().strip() in ['cancel'], state='*')
|
||||
|
||||
|
|
@ -126,18 +126,18 @@ async def on_startup(app):
|
|||
|
||||
# If URL is bad
|
||||
if webhook.url != WEBHOOK_URL:
|
||||
# If URL doesnt match with by current remove webhook
|
||||
# If URL doesnt match current - remove webhook
|
||||
if not webhook.url:
|
||||
await bot.delete_webhook()
|
||||
|
||||
# Set new URL for webhook
|
||||
await bot.set_webhook(WEBHOOK_URL, certificate=open(WEBHOOK_SSL_CERT, 'rb'))
|
||||
# If you want to use free certificate signed by LetsEncrypt need to set only URL without sending certificate.
|
||||
# If you want to use free certificate signed by LetsEncrypt you need to set only URL without sending certificate.
|
||||
|
||||
|
||||
async def on_shutdown(app):
|
||||
"""
|
||||
Graceful shutdown. This method is recommended by aiohttp doc's.
|
||||
Graceful shutdown. This method is recommended by aiohttp docs.
|
||||
"""
|
||||
# Remove webhook.
|
||||
await bot.delete_webhook()
|
||||
|
|
@ -162,5 +162,5 @@ if __name__ == '__main__':
|
|||
# Start web-application.
|
||||
web.run_app(app, host=WEBHOOK_HOST, port=WEBHOOK_PORT, ssl_context=context)
|
||||
# Note:
|
||||
# If you should start bot over nginx or Apache web server SSL context is not required here.
|
||||
# Otherwise you need to set that parameter.
|
||||
# If you start your bot using nginx or Apache web server, SSL context is not required.
|
||||
# Otherwise you need to set `ssl_context` parameter.
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue