-
Notifications
You must be signed in to change notification settings - Fork 47
22ПИ-1 Овсянников #18
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
base: main
Are you sure you want to change the base?
Changes from all commits
36a7d29
e93858e
53ca25a
2496cb7
4865ba1
b6324b8
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -356,3 +356,5 @@ dmypy.json | |
| # Cython debug symbols | ||
| cython_debug/ | ||
|
|
||
| # Config of todo bot | ||
| todobot/config.py | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| from todobot.bot import main | ||
|
|
||
| if __name__ == '__main__': | ||
| main() |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,128 @@ | ||
| # !/usr/bin/env python | ||
| # pylint: disable=unused-argument | ||
| # This program is dedicated to the public domain under the CC0 license. | ||
|
|
||
| """ | ||
| Simple Bot to reply to Telegram messages. | ||
|
|
||
| First, a few handler functions are defined. Then, those functions are passed to | ||
| the Application and registered at their respective places. | ||
| Then, the bot is started and runs until we press Ctrl-C on the command line. | ||
|
|
||
| Usage: | ||
| Basic Echobot example, repeats messages. | ||
| Press Ctrl-C on the command line or send a signal to the process to stop the | ||
| bot. | ||
| """ | ||
|
|
||
| import logging | ||
|
|
||
| from telegram import Update | ||
| from telegram.ext import ( | ||
| Application, | ||
| CommandHandler, | ||
| ContextTypes, | ||
| MessageHandler, | ||
| filters, | ||
| ) | ||
| from todobot.config import TELEGRAM_TOKEN | ||
|
|
||
|
|
||
| TASKS: dict[int, list[str]] = dict() | ||
|
|
||
| # Enable logging | ||
| logging.basicConfig( | ||
| format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO | ||
| ) | ||
| # set higher logging level for httpx to avoid all GET and POST requests being logged | ||
| logging.getLogger("httpx").setLevel(logging.WARNING) | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| # Define a few command handlers. These usually take the two arguments update and | ||
| # context. | ||
| async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: | ||
| """Send a message when the command /start is issued.""" | ||
| user = update.effective_user | ||
| await update.message.reply_text("Hello, my friend!") | ||
| await update.message.reply_text("I'm todo bot and I can add tasks to your list! 😃") | ||
|
|
||
|
|
||
| async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: | ||
| """Send a message when the command /help is issued.""" | ||
| await update.message.reply_text("Help!") | ||
|
|
||
|
|
||
| async def add_task(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: | ||
| """Add new task using /add command.""" | ||
| user = update.effective_user | ||
| task_description = " ".join(context.args) | ||
|
|
||
| if not task_description: | ||
| await update.message.reply_text("Please provide a task description.") | ||
| return | ||
| else: | ||
| TASKS.setdefault(user.id, []).append(task_description) | ||
| tasks = "\n".join(TASKS[user.id]) | ||
| message = f"Task added to list. All list:\n{tasks}" | ||
| await update.message.reply_text(message) | ||
|
|
||
|
|
||
| async def remove_task(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: | ||
| """Remove a task using /remove command.""" | ||
| user = update.effective_user | ||
| args = context.args | ||
| if not args: | ||
| await update.message.reply_text( | ||
| "Please provide a task description or a task index." | ||
| ) | ||
| return | ||
sh1ronchik marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| # Check if the argument is a task description or a task index | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. подумай как лучше переформатировать этот код, много повторений и см комменты ниже |
||
| try: | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. в try except старайся оборачивать только тот участок кода, который действительно может упасть полтона кода писать в рамках этих операторов плохая практика - часто возникают проблемы с локализацией ошибки и тд |
||
| task_index = int(args[0]) - 1 | ||
| tasks = TASKS.get(user.id, []) | ||
| if 0 <= task_index < len(tasks): | ||
| removed_task = tasks.pop(task_index) | ||
| await update.message.reply_text(f"Removed task: {removed_task}") | ||
| else: | ||
| await update.message.reply_text("Invalid task index.") | ||
| except ValueError: | ||
| task_description = " ".join(args) | ||
| tasks = TASKS.get(user.id, []) | ||
| if task_description in tasks: | ||
| tasks.remove(task_description) | ||
| await update.message.reply_text(f"Removed task: {task_description}") | ||
| else: | ||
| await update.message.reply_text("Task not found.") | ||
|
|
||
|
|
||
| async def view_tasks(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: | ||
| """View all tasks in the user's list.""" | ||
| user = update.effective_user | ||
| tasks = TASKS.get(user.id, []) | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. я бы вынес в отдельную функцию, так ты таскаешь дефолтное поведение везде а по хорошему - вообще бы сделал отдельный класс или модуль storage с которым оперировал через методы.функции |
||
| if tasks: | ||
| tasks_message = "\n".join(tasks) | ||
| await update.message.reply_text(f"Your tasks:\n{tasks_message}") | ||
sh1ronchik marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| else: | ||
| await update.message.reply_text("You have no tasks.") | ||
|
|
||
|
|
||
| def main() -> None: | ||
| """Start the bot.""" | ||
| # Create the Application and pass it your bot's token. | ||
| application = Application.builder().token(TELEGRAM_TOKEN).build() | ||
|
|
||
| # on different commands - answer in Telegram | ||
| application.add_handler(CommandHandler("start", start)) | ||
| application.add_handler(CommandHandler("help", help_command)) | ||
| application.add_handler(CommandHandler("add", add_task)) | ||
| application.add_handler(CommandHandler("remove", remove_task)) | ||
| application.add_handler(CommandHandler("view", view_tasks)) | ||
|
|
||
| # on non command i.e message - echo the message on Telegram | ||
| application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, add_task)) | ||
|
|
||
| # Run the bot until the user presses Ctrl-C | ||
| application.run_polling(allowed_updates=Update.ALL_TYPES) | ||
Uh oh!
There was an error while loading. Please reload this page.