-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
79 lines (56 loc) · 2.07 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import feedparser
from datetime import datetime, timedelta, timezone
import sqlite3
import discord
from discord.ext import commands, tasks
from config import TOKEN, CHANNEL_ID, UPDATE_INTERVAL, LAST_ARTICLE_RANGE, RSS_FEEDS
connection = sqlite3.connect('articles.db')
c = connection.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS articles (title TEXT, link TEXT)''')
connection.commit()
bot = commands.Bot(command_prefix='!', intents=discord.Intents.all())
def record_article_in_db(article):
c.execute("INSERT INTO articles (title, link) VALUES (?, ?)", (article.title, article.link))
connection.commit()
def article_in_db(entry):
c.execute("SELECT link FROM articles WHERE link=?", (entry.link,))
if c.fetchone() is None:
return False
else:
return True
def get_new_articles():
new_articles = []
for rss_feed in RSS_FEEDS:
entries = feedparser.parse(rss_feed["url"]).entries
for entry in entries:
if not article_in_db(entry):
pub_date = datetime.strptime(entry.published, "%a, %d %b %Y %H:%M:%S %z").replace(tzinfo=timezone.utc)
if datetime.now(timezone.utc) - pub_date <= timedelta(days=LAST_ARTICLE_RANGE):
new_articles.append({"article": entry, "user": rss_feed["user"], "feedTitle": feedparser.parse(rss_feed["url"]).feed.title})
return new_articles
def format_to_message(article):
article_title = article["article"].title
article_user = article["user"]
article_feed_title = article["feedTitle"]
article_link = article["article"].link
message = f"**{article_title}** by "
if article_user:
message += f"<@{article_user}>"
else:
message += f"{article_feed_title}"
message += f"\n{article_link}"
return message
@bot.event
async def on_ready():
print(f'{bot.user} has connected to Discord!')
post_new_articles.start()
@tasks.loop(minutes=UPDATE_INTERVAL)
async def post_new_articles():
channel = bot.get_channel(CHANNEL_ID)
new_articles = get_new_articles()
for article in new_articles:
message = format_to_message(article)
await channel.send(message)
record_article_in_db(article["article"])
if __name__ == "__main__":
bot.run(TOKEN)