Добавить второй блок новостей в !news, !morning и console morning

This commit is contained in:
deadzilla 2026-05-26 21:25:14 +05:00
parent cc6ed5c183
commit 7bc5bae413
3 changed files with 108 additions and 28 deletions

View File

@ -3,7 +3,8 @@ import asyncio
import discord import discord
from discord.ext import commands from discord.ext import commands
from utils.pogoda import fetch_weather, pressure_to_mmhg, translate_weather from utils.pogoda import fetch_weather, pressure_to_mmhg, translate_weather
from utils.news import fetch_rss, format_articles, RSS_URL_ARTICLES from utils.news import fetch_rss, format_articles, RSS_URL_ARTICLES, RSS_URL_POSTS
from utils.cat import fetch_cat
class Morning(commands.Cog): class Morning(commands.Cog):
@ -14,14 +15,23 @@ class Morning(commands.Cog):
@commands.command(name="morning") @commands.command(name="morning")
async def morning(self, ctx): async def morning(self, ctx):
"""Погода и лучшие статьи за сутки""" """Погода, лучшие статьи за сутки и котик"""
# Параллельный запрос погоды и новостей # Параллельный запрос погоды, новостей и котика
weather_data, articles = await asyncio.gather( weather_data, articles, posts, cat_url = await asyncio.gather(
fetch_weather(self.api_url), fetch_weather(self.api_url),
fetch_rss(RSS_URL_ARTICLES), fetch_rss(RSS_URL_ARTICLES),
fetch_rss(RSS_URL_POSTS),
fetch_cat(),
) )
parts = ["Доброе утро!\n"] # --- Формируем embed ---
embed = discord.Embed(title="Доброе утро!", color=0xF4A460)
# Котик как thumbnail (маленький в углу)
if cat_url:
embed.set_thumbnail(url=cat_url)
description_lines = []
# --- Погода --- # --- Погода ---
if weather_data is not None: if weather_data is not None:
@ -39,29 +49,47 @@ class Morning(commands.Cog):
pressure_mb = current.get("pressure", "\u2014") pressure_mb = current.get("pressure", "\u2014")
pressure_mm = pressure_to_mmhg(pressure_mb) pressure_mm = pressure_to_mmhg(pressure_mb)
parts.append( description_lines.append(
f"**Погода в Магнитогорске:**\n" f"**Погода в Магнитогорске:**\n"
f"Температура: {temp}\u00b0C (ощущается как {feels_like}\u00b0C)\n" f"Температура: {temp}\u00b0C (ощущается как {feels_like}\u00b0C)\n"
f"Описание: {description}\n" f"Описание: {description}\n"
f"Влажность: {humidity}%\n" f"Влажность: {humidity}%\n"
f"Ветер: {wind} м/с\n" f"Ветер: {wind} м/с\n"
f"Давление: {pressure_mm} мм рт. ст.\n" f"Давление: {pressure_mm} мм рт. ст."
) )
else: else:
parts.append("Не удалось получить данные о погоде.\n") description_lines.append("Не удалось получить данные о погоде.")
else: else:
parts.append("Не удалось получить данные о погоде.\n") description_lines.append("Не удалось получить данные о погоде.")
# --- Новости --- description_lines.append("") # пустая строка-разделитель
# --- Новости: статьи ---
if articles is not None: if articles is not None:
if articles: if articles:
lines = format_articles(articles, lines = format_articles(articles,
"Лучшие статьи за сутки / Искусственный интеллект / Хабr", "Лучшие статьи за сутки / Искусственный интеллект / Хабr",
"https://habr.com/ru/hubs/artificial_intelligence/articles/top/daily/") "https://habr.com/ru/hubs/artificial_intelligence/articles/top/daily/")
parts.append("\n" + "\n".join(lines).rstrip()) description_lines.append("\n".join(lines))
else: else:
parts.append("\nНовостей пока нет.") description_lines.append("Новостей пока нет.")
else: else:
parts.append("\nНе удалось получить новости.") description_lines.append("Не удалось получить новости.")
await ctx.send("\n".join(parts)) description_lines.append("") # пустая строка-разделитель
# --- Новости: посты ---
if posts is not None:
if posts:
lines = format_articles(posts,
"Лучшие новости за сутки / Искусственный интеллект / Хабr",
"https://habr.com/ru/hubs/artificial_intelligence/news/top/daily/")
description_lines.append("\n".join(lines))
else:
description_lines.append("Новостей пока нет.")
else:
description_lines.append("Не удалось получить новости.")
embed.description = "\n".join(description_lines)
await ctx.send(embed=embed)

View File

@ -8,7 +8,7 @@ class News(commands.Cog):
@commands.command(name="news") @commands.command(name="news")
async def news(self, ctx): async def news(self, ctx):
"""Топ-5 свежих статей по AI с Habr""" """Топ-5 свежих статей и новостей по AI с Habr"""
articles = await fetch_rss(RSS_URL_ARTICLES) articles = await fetch_rss(RSS_URL_ARTICLES)
if articles is None: if articles is None:
await ctx.send("Не удалось получить новости. Попробуйте позже.") await ctx.send("Не удалось получить новости. Попробуйте позже.")
@ -18,14 +18,43 @@ class News(commands.Cog):
await ctx.send("Новостей пока нет.") await ctx.send("Новостей пока нет.")
return return
lines = format_articles(articles, "Лучшие статьи за сутки / Искусственный интеллект / Хабr", articles_text = format_articles(articles,
"https://habr.com/ru/hubs/artificial_intelligence/articles/top/daily/") "Лучшие статьи за сутки / Искусственный интеллект / Хабr",
"https://habr.com/ru/hubs/artificial_intelligence/articles/top/daily/")
posts = await fetch_rss(RSS_URL_POSTS) posts = await fetch_rss(RSS_URL_POSTS)
if posts:
lines.append("")
lines.extend(format_articles(posts, "Лучшие новости за сутки / Искусственный интеллект / Хабr",
"https://habr.com/ru/hubs/artificial_intelligence/news/top/daily/"))
message = "\n".join(lines).rstrip() embed = discord.Embed(
await ctx.send(message, allowed_mentions=discord.AllowedMentions.none()) title="Новости AI с Habr",
colour=discord.Color.orange(),
)
embed.add_field(
name="Статьи",
value="\n".join(articles_text),
inline=False,
)
if posts is None:
embed.add_field(
name="Новости",
value="Не удалось получить новости.",
inline=False,
)
elif posts:
posts_text = format_articles(posts,
"Лучшие новости за сутки / Искусственный интеллект / Хабr",
"https://habr.com/ru/hubs/artificial_intelligence/news/top/daily/")
embed.add_field(
name="Новости",
value="\n".join(posts_text),
inline=False,
)
else:
embed.add_field(
name="Новости",
value="Новостей пока нет.",
inline=False,
)
await ctx.send(embed=embed)

View File

@ -1,21 +1,30 @@
import asyncio import asyncio
from utils.pogoda import fetch_weather, pressure_to_mmhg, translate_weather from utils.pogoda import fetch_weather, pressure_to_mmhg, translate_weather
from utils.news import fetch_rss, format_articles, RSS_URL_ARTICLES from utils.news import fetch_rss, format_articles, RSS_URL_ARTICLES, RSS_URL_POSTS
from utils.cat import fetch_cat
async def morning(stop_event, bot): async def morning(stop_event, bot):
"""Вывести погоду и лучшие статьи за сутки""" """Вывести погоду, лучшие статьи за сутки и котика"""
api_url = "https://wttr.in/Magnitogorsk?format=j1&lang=ru" api_url = "https://wttr.in/Magnitogorsk?format=j1&lang=ru"
# Параллельный запрос погоды и новостей # Параллельный запрос погоды, новостей и котика
weather_data, articles = await asyncio.gather( weather_data, articles, posts, cat_url = await asyncio.gather(
fetch_weather(api_url), fetch_weather(api_url),
fetch_rss(RSS_URL_ARTICLES), fetch_rss(RSS_URL_ARTICLES),
fetch_rss(RSS_URL_POSTS),
fetch_cat(),
) )
print("Доброе утро!\n") print("Доброе утро!\n")
# --- Котик ---
if cat_url:
print(f"Котик: {cat_url}\n")
else:
print("Котика получить не удалось.\n")
# --- Погода --- # --- Погода ---
if weather_data is not None: if weather_data is not None:
current = weather_data.get("current_condition", [{}])[0] current = weather_data.get("current_condition", [{}])[0]
@ -45,7 +54,7 @@ async def morning(stop_event, bot):
print() print()
# --- Новости --- # --- Новости: статьи ---
if articles is not None: if articles is not None:
if articles: if articles:
lines = format_articles(articles, lines = format_articles(articles,
@ -56,3 +65,17 @@ async def morning(stop_event, bot):
print("Новостей пока нет.") print("Новостей пока нет.")
else: else:
print("Не удалось получить новости.") print("Не удалось получить новости.")
print()
# --- Новости: посты ---
if posts is not None:
if posts:
lines = format_articles(posts,
"Лучшие новости за сутки / Искусственный интеллект / Хабr",
"https://habr.com/ru/hubs/artificial_intelligence/news/top/daily/")
print("\n".join(lines))
else:
print("Новостей пока нет.")
else:
print("Не удалось получить новости.")