From d2e068d527500b637601913a1df607840cfddbaa Mon Sep 17 00:00:00 2001 From: Ian Andwati Date: Wed, 27 Sep 2023 03:20:04 +0300 Subject: [PATCH] implemented random pic functionality --- .env.example | 3 +++ poetry.lock | 2 +- pyproject.toml | 1 + unsplashbot/bot.py | 18 ++++++++++++++---- unsplashbot/config.py | 4 ++++ unsplashbot/unsplash_api.py | 0 6 files changed, 23 insertions(+), 5 deletions(-) create mode 100644 unsplashbot/unsplash_api.py diff --git a/.env.example b/.env.example index e69de29..2816445 100644 --- a/.env.example +++ b/.env.example @@ -0,0 +1,3 @@ +TELEGRAM_TOKEN= +ACCESS_KEY= +SECRET_KEY= diff --git a/poetry.lock b/poetry.lock index 9f8fca7..9d1afe9 100644 --- a/poetry.lock +++ b/poetry.lock @@ -552,4 +552,4 @@ watchdog = ["watchdog (>=2.3)"] [metadata] lock-version = "2.0" python-versions = "^3.11" -content-hash = "d51a7ed0e1456398f57862f5a44db12017266f0723bc5123679fc751dbf617a9" +content-hash = "5722f06b58085e44f0359d02884aa1de8f1bac83c9d9dd55b7eef024327a48cc" diff --git a/pyproject.toml b/pyproject.toml index 8e56e75..f372391 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -10,6 +10,7 @@ python = "^3.11" flask = "^2.3.3" python-dotenv = "^1.0.0" pytelegrambotapi = "^4.14.0" +requests = "^2.31.0" [tool.poetry.group.dev.dependencies] pre-commit = "^3.4.0" diff --git a/unsplashbot/bot.py b/unsplashbot/bot.py index e0588d6..396ec47 100644 --- a/unsplashbot/bot.py +++ b/unsplashbot/bot.py @@ -1,5 +1,6 @@ +import requests import telebot -from config import TELEGRAM_TOKEN +from config import ACCESS_TOKEN, BASE_URL, TELEGRAM_TOKEN bot = telebot.TeleBot(TELEGRAM_TOKEN) @@ -9,9 +10,18 @@ def send_welcome(message): bot.reply_to(message, "Hello, I'm a bot!") -@bot.message_handler(func=lambda msg: True) -def echo_all(message): - bot.reply_to(message, message.text) +@bot.message_handler(commands=["random"]) +def get_random_photo(message): + url = "https://api.unsplash.com/photos/random" + response = requests.get( + url, timeout=10, headers={"Authorization": f"Client-ID {ACCESS_TOKEN}"} + ) + data = response.json() + image_url = data["urls"]["regular"] + description = data["alt_description"] + image_content = requests.get(image_url) + + bot.send_photo(message.chat.id, image_content.content, caption=description) bot.infinity_polling() diff --git a/unsplashbot/config.py b/unsplashbot/config.py index 8b0b021..a9c926f 100644 --- a/unsplashbot/config.py +++ b/unsplashbot/config.py @@ -5,3 +5,7 @@ from dotenv import load_dotenv load_dotenv() TELEGRAM_TOKEN = os.getenv("TELEGRAM_TOKEN") +ACCESS_TOKEN = os.getenv("ACCESS_KEY") +SECRET_KEY = os.getenv("SECRET_KEY") + +BASE_URL = "https://api.unsplash.com" diff --git a/unsplashbot/unsplash_api.py b/unsplashbot/unsplash_api.py new file mode 100644 index 0000000..e69de29