-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.py
200 lines (162 loc) · 5.46 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
import os
import discord
import asyncio
import datetime
import traceback
import json
import whatsapp
from discord.ext import commands, tasks
from get_news import get_news
from replit import db
from json import JSONEncoder
from news_class import dictToNews
from keep_alive import keep_alive
# Cria uma classe para permitir que as instâncias de News sejam serializadas
class NewsEncoder(JSONEncoder):
def default(self, o):
return o.__dict__
bot = commands.Bot(command_prefix="&", intents=discord.Intents.all())
current_news = {}
def load_news():
# Carrega da memória as notícias já enviadas
global current_news
loaded_news = json.loads(db['current_news'])
current_news = {}
for k in loaded_news:
l = []
for e in loaded_news[k]:
l.append(dictToNews(e))
current_news[k] = l
def update_db():
db['current_news'] = json.dumps(current_news, indent=6, cls=NewsEncoder)
async def send_news(nlist: list, guild):
for n in nlist:
embed = discord.Embed(
colour=discord.Colour.dark_gold(),
title=n.title,
description=n.description,
url=n.link
)
embed.set_image(url=n.thumbnail)
channels = guild.text_channels
for channel in channels:
if channel.is_news():
await channel.send(embed=embed)
break
@tasks.loop(hours=1)
async def update_news():
load_news()
global current_news
for guild in bot.guilds:
cnews_guild = current_news.get(str(guild.id), [])
try:
news = get_news(db[str(guild.id)])
except Exception as e:
print(type(e))
traceback.print_exc()
# Create a list of news to send
new_news = [n for n in news if n not in cnews_guild]
if len(new_news > 10):
whatsapp.send_alert(guild.id)
continue
if new_news:
updated = False
try:
await send_news(new_news, guild.id)
if guild.id == 893328736051683329:
whatsapp.send_news(new_news)
except Exception as e:
print(e)
print(type(e))
traceback.print_exc()
else:
updated = True
if not updated:
current_news[str(guild.id)] = news
update_db()
log = open("debug.log", 'a')
log.write(f"""
LOG: Updated \"current_news\"\n
NEWS_DB: {cnews_guild}\n\n""")
log.close()
# Verifica quanto tempo até a próxima hora completa e dorme o loop até a mesma
@update_news.before_loop
async def looper():
delta = datetime.timedelta(hours=1)
now = datetime.datetime.now()
next_hour = (now+delta).replace(microsecond=0, second=0, minute=0)
await asyncio.sleep((next_hour-now).seconds)
@bot.event
async def on_ready():
print(f"Bot iniciado como: {bot.user}")
load_news()
@bot.event
async def on_guild_join(guild):
sys_channel = guild.system_channel
db[guild.id] = "caruaru"
if sys_channel:
try:
await sys_channel.send("Utilize o comando \"&alterarcampus (seucampus)\" para definir de qual campi as notificações serão enviadas!")
except Exception as e:
print(
f"!!Não foi possível solicitar definição de campus no servidor: {guild.name}!!\nError:{e}\n\n")
@bot.command(pass_context=True)
@commands.has_permissions(administrator=True)
async def alterarcampus(ctx, campus):
db[ctx.guild.id] = str(campus)
await ctx.channel.send(f"Campus alterado com sucesso para {campus}")
@alterarcampus.error
async def alterarcampus_error(ctx, error):
if isinstance(error, commands.CheckFailure):
msg = "Você não tem permissão para executar essa ação, peça à um administrador!"
await ctx.send(msg)
@bot.command(pass_context=True)
@commands.has_permissions(administrator=True)
async def atualizarmanual(ctx):
global current_news
guild_id = ctx.guild.id
cnews_guild = current_news.get(str(guild_id))
try:
news = get_news(db[str(guild_id)])
except Exception as e:
print(type(e))
traceback.print_exc()
updated = True
for n in news:
if cnews_guild:
verification = n not in cnews_guild
if verification:
updated = False
await send_news(n, ctx.guild)
else:
try:
updated = False
await send_news(n, ctx.guild)
except Exception as e:
print(e)
print(type(e))
traceback.print_exc()
if not updated:
current_news[str(guild_id)] = news
print(
f"Manually updated by: {ctx.author}\n{datetime.datetime.now()}\n")
try:
update_db()
await ctx.send("As notícias foram atualizadas com sucesso!")
except Exception as e:
print(e)
print(type(e))
traceback.print_exc()
else:
await ctx.send("Notícias já atualizadas!")
@atualizarmanual.error
async def atualizarmanual_error(ctx, error):
if isinstance(error, commands.CheckFailure):
msg = "Você não tem permissão para executar essa ação, peça à um administrador!"
await ctx.send(msg)
@bot.command(pass_context=True)
async def massupdate(ctx):
await update_news()
update_news.start()
keep_alive()
bot.run(os.environ['DISCORD-BOT-TOKEN'])