feat: обновить формат новостей (заголовок/дата+ссылка), добавить блок новостей с habr.com/ru/rss/hubs/artificial_intelligence/news/

This commit is contained in:
deadzilla 2026-05-25 23:58:54 +05:00
parent d5911b226d
commit 3f921680cf
2 changed files with 59 additions and 20 deletions

View File

@ -4,7 +4,8 @@ import requests
from xml.etree import ElementTree
RSS_URL = "https://habr.com/ru/rss/hubs/artificial_intelligence/articles/rated10/?fl=ru"
RSS_URL_ARTICLES = "https://habr.com/ru/rss/hubs/artificial_intelligence/articles/top/daily/?fl=ru"
RSS_URL_POSTS = "https://habr.com/ru/rss/hubs/artificial_intelligence/news/top/daily/?fl=ru"
class News(commands.Cog):
@ -13,7 +14,7 @@ class News(commands.Cog):
@commands.command(name="news")
async def news(self, ctx):
"""Топ-5 свежих статей по AI с Habr"""
articles = self._fetch_rss()
articles = self._fetch_rss(RSS_URL_ARTICLES)
if articles is None:
await ctx.send("Не удалось получить новости. Попробуйте позже.")
return
@ -24,10 +25,10 @@ class News(commands.Cog):
await self._format_and_send(ctx, articles)
def _fetch_rss(self):
def _fetch_rss(self, url):
"""Скачать и распарсить RSS-ленту (RSS 2.0 / Atom)."""
try:
response = requests.get(RSS_URL, timeout=10)
response = requests.get(url, timeout=10)
response.raise_for_status()
root = ElementTree.fromstring(response.content)
@ -81,7 +82,7 @@ class News(commands.Cog):
async def _format_and_send(self, ctx, articles):
"""Сформировать текст и отправить в чат."""
lines = ["**🤖 AI-новости с Habr**"]
lines = ["**Лучшие статьи за сутки / Искусственный интеллект / Хабr**\n<https://habr.com/ru/hubs/artificial_intelligence/articles/top/daily/>\n"]
for i, article in enumerate(articles[:5], 1):
from datetime import datetime
date_str = ""
@ -92,14 +93,30 @@ class News(commands.Cog):
date_str = dt.strftime("%d.%m.%Y")
except ValueError:
date_str = article["pub_date"][:10].replace("-", ".")
tags_str = ", ".join(article["tags"][:3]) if article["tags"] else ""
title = article["title"]
if len(title) > 60:
title = title[:60] + "..."
lines.append(f"{i}. {title}")
lines.append(f" {article['creator']} | {date_str} | {tags_str} ")
link = article["link"].replace("https://", "")
lines.append(f" {link}")
lines.append(f"{title}\n{date_str} <{article['link']}>")
# Второй блок: посты
posts = self._fetch_rss(RSS_URL_POSTS)
if posts:
lines.append("")
lines.append("**Лучшие новости за сутки / Искусственный интеллект / Хабr**\n<https://habr.com/ru/hubs/artificial_intelligence/news/top/daily/>\n")
for i, article in enumerate(posts[:5], 1):
from datetime import datetime
date_str = ""
if article["pub_date"]:
try:
d = article["pub_date"].replace(" GMT", " +0000")
dt = datetime.strptime(d, "%a, %d %b %Y %H:%M:%S %z")
date_str = dt.strftime("%d.%m.%Y")
except ValueError:
date_str = article["pub_date"][:10].replace("-", ".")
title = article["title"]
if len(title) > 60:
title = title[:60] + "..."
lines.append(f"{title}\n{date_str} <{article['link']}>")
message = "\n".join(lines).rstrip()
await ctx.send(message, allowed_mentions=discord.AllowedMentions.none())

View File

@ -2,12 +2,13 @@ import requests
from xml.etree import ElementTree
RSS_URL = "https://habr.com/ru/rss/hubs/artificial_intelligence/articles/rated10/?fl=ru"
RSS_URL_ARTICLES = "https://habr.com/ru/rss/hubs/artificial_intelligence/articles/top/daily/?fl=ru"
RSS_URL_POSTS = "https://habr.com/ru/rss/hubs/artificial_intelligence/news/top/daily/?fl=ru"
def news(stop_event, bot):
"""Вывести топ-5 свежих статей по AI с Habr"""
articles = _fetch_rss()
articles = _fetch_rss(RSS_URL_ARTICLES)
if articles is None:
print("Не удалось получить новости.")
return
@ -17,7 +18,9 @@ def news(stop_event, bot):
return
from datetime import datetime
print("**AI-новости с Habr**")
print("**Лучшие статьи за сутки / Искусственный интеллект / Хабr**")
print("<https://habr.com/ru/hubs/artificial_intelligence/articles/top/daily/>")
print()
for i, article in enumerate(articles[:5], 1):
date_str = ""
if article["pub_date"]:
@ -27,21 +30,40 @@ def news(stop_event, bot):
date_str = dt.strftime("%d.%m.%Y")
except ValueError:
date_str = article["pub_date"][:10].replace("-", ".")
tags_str = ", ".join(article["tags"][:3]) if article["tags"] else ""
link = article["link"].replace("https://", "")
title = article["title"]
if len(title) > 60:
title = title[:60] + "..."
print(f"{i}. {title}")
print(f" {article['creator']} | {date_str} | {tags_str}")
print(f" {link}")
print(f"{title}\n {date_str} {article['link']}")
print("────────────────────────────────────────")
print()
# Второй блок: посты
posts = _fetch_rss(RSS_URL_POSTS)
if posts:
print("**Лучшие новости за сутки / Искусственный интеллект / Хабr**")
print("<https://habr.com/ru/hubs/artificial_intelligence/news/top/daily/>")
print()
for i, article in enumerate(posts[:5], 1):
date_str = ""
if article["pub_date"]:
try:
d = article["pub_date"].replace(" GMT", " +0000")
dt = datetime.strptime(d, "%a, %d %b %Y %H:%M:%S %z")
date_str = dt.strftime("%d.%m.%Y")
except ValueError:
date_str = article["pub_date"][:10].replace("-", ".")
title = article["title"]
if len(title) > 60:
title = title[:60] + "..."
print(f"{title}\n {date_str} {article['link']}")
print("────────────────────────────────────────")
print()
def _fetch_rss():
def _fetch_rss(url):
"""Скачать и распарсить RSS-ленту (RSS 2.0 / Atom)."""
try:
response = requests.get(RSS_URL, timeout=10)
response = requests.get(url, timeout=10)
response.raise_for_status()
root = ElementTree.fromstring(response.content)