feat: обновить формат новостей (заголовок/дата+ссылка), добавить блок новостей с habr.com/ru/rss/hubs/artificial_intelligence/news/
This commit is contained in:
parent
4db31e8b56
commit
78ad6fb3bb
@ -4,7 +4,8 @@ import requests
|
|||||||
from xml.etree import ElementTree
|
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):
|
class News(commands.Cog):
|
||||||
@ -13,7 +14,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 = self._fetch_rss()
|
articles = self._fetch_rss(RSS_URL_ARTICLES)
|
||||||
if articles is None:
|
if articles is None:
|
||||||
await ctx.send("Не удалось получить новости. Попробуйте позже.")
|
await ctx.send("Не удалось получить новости. Попробуйте позже.")
|
||||||
return
|
return
|
||||||
@ -24,10 +25,10 @@ class News(commands.Cog):
|
|||||||
|
|
||||||
await self._format_and_send(ctx, articles)
|
await self._format_and_send(ctx, articles)
|
||||||
|
|
||||||
def _fetch_rss(self):
|
def _fetch_rss(self, url):
|
||||||
"""Скачать и распарсить RSS-ленту (RSS 2.0 / Atom)."""
|
"""Скачать и распарсить RSS-ленту (RSS 2.0 / Atom)."""
|
||||||
try:
|
try:
|
||||||
response = requests.get(RSS_URL, timeout=10)
|
response = requests.get(url, timeout=10)
|
||||||
response.raise_for_status()
|
response.raise_for_status()
|
||||||
root = ElementTree.fromstring(response.content)
|
root = ElementTree.fromstring(response.content)
|
||||||
|
|
||||||
@ -81,7 +82,7 @@ class News(commands.Cog):
|
|||||||
|
|
||||||
async def _format_and_send(self, ctx, articles):
|
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):
|
for i, article in enumerate(articles[:5], 1):
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
date_str = ""
|
date_str = ""
|
||||||
@ -92,14 +93,30 @@ class News(commands.Cog):
|
|||||||
date_str = dt.strftime("%d.%m.%Y")
|
date_str = dt.strftime("%d.%m.%Y")
|
||||||
except ValueError:
|
except ValueError:
|
||||||
date_str = article["pub_date"][:10].replace("-", ".")
|
date_str = article["pub_date"][:10].replace("-", ".")
|
||||||
tags_str = ", ".join(article["tags"][:3]) if article["tags"] else ""
|
|
||||||
title = article["title"]
|
title = article["title"]
|
||||||
if len(title) > 60:
|
if len(title) > 60:
|
||||||
title = title[:60] + "..."
|
title = title[:60] + "..."
|
||||||
lines.append(f"{i}. {title}")
|
lines.append(f"{title}\n{date_str} <{article['link']}>")
|
||||||
lines.append(f" {article['creator']} | {date_str} | {tags_str} ")
|
|
||||||
link = article["link"].replace("https://", "")
|
# Второй блок: посты
|
||||||
lines.append(f" {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()
|
message = "\n".join(lines).rstrip()
|
||||||
await ctx.send(message, allowed_mentions=discord.AllowedMentions.none())
|
await ctx.send(message, allowed_mentions=discord.AllowedMentions.none())
|
||||||
|
|||||||
@ -2,12 +2,13 @@ import requests
|
|||||||
from xml.etree import ElementTree
|
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):
|
def news(stop_event, bot):
|
||||||
"""Вывести топ-5 свежих статей по AI с Habr"""
|
"""Вывести топ-5 свежих статей по AI с Habr"""
|
||||||
articles = _fetch_rss()
|
articles = _fetch_rss(RSS_URL_ARTICLES)
|
||||||
if articles is None:
|
if articles is None:
|
||||||
print("Не удалось получить новости.")
|
print("Не удалось получить новости.")
|
||||||
return
|
return
|
||||||
@ -17,7 +18,9 @@ def news(stop_event, bot):
|
|||||||
return
|
return
|
||||||
|
|
||||||
from datetime import datetime
|
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):
|
for i, article in enumerate(articles[:5], 1):
|
||||||
date_str = ""
|
date_str = ""
|
||||||
if article["pub_date"]:
|
if article["pub_date"]:
|
||||||
@ -27,21 +30,40 @@ def news(stop_event, bot):
|
|||||||
date_str = dt.strftime("%d.%m.%Y")
|
date_str = dt.strftime("%d.%m.%Y")
|
||||||
except ValueError:
|
except ValueError:
|
||||||
date_str = article["pub_date"][:10].replace("-", ".")
|
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"]
|
title = article["title"]
|
||||||
if len(title) > 60:
|
if len(title) > 60:
|
||||||
title = title[:60] + "..."
|
title = title[:60] + "..."
|
||||||
print(f"{i}. {title}")
|
print(f"{title}\n {date_str} {article['link']}")
|
||||||
print(f" {article['creator']} | {date_str} | {tags_str}")
|
print("────────────────────────────────────────")
|
||||||
print(f" {link}")
|
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()
|
print()
|
||||||
|
|
||||||
|
|
||||||
def _fetch_rss():
|
def _fetch_rss(url):
|
||||||
"""Скачать и распарсить RSS-ленту (RSS 2.0 / Atom)."""
|
"""Скачать и распарсить RSS-ленту (RSS 2.0 / Atom)."""
|
||||||
try:
|
try:
|
||||||
response = requests.get(RSS_URL, timeout=10)
|
response = requests.get(url, timeout=10)
|
||||||
response.raise_for_status()
|
response.raise_for_status()
|
||||||
root = ElementTree.fromstring(response.content)
|
root = ElementTree.fromstring(response.content)
|
||||||
|
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user