forked from Larenthios/Nebubot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnebubot.py
executable file
·280 lines (241 loc) · 9.74 KB
/
nebubot.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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
#! /usr/bin/env python3
import discord
from discord.ext import commands
import asyncio
import datetime
import configparser
import csv
import os
#doc api discord http://discordpy.readthedocs.io/en/latest/api.html
#doc discord.py https://discordpy.readthedocs.io/en/rewrite/index.html
bot = commands.Bot(command_prefix='.', description='h')
#on pars le fichier config pour recup les infos que l'on a besoin pour se connecter
config = configparser.ConfigParser()
config.read('config.ini')
token = config['keys']['discord_nebula']
general_channel_id = config['chan_id']['test']
class Event(object):
dt = 0
str = ""
desc = ""
def __init__(self, datetime, desc : str):
self.dt = datetime
self.str = datetime.strftime("%Hh%M %d/%m/%Y")
self.desc = desc
async def check_event():
await bot.wait_until_ready()
today = datetime.datetime.today()
margin = datetime.timedelta(days = 3)
event_tab = []
for row in csv.reader(open('dates.csv', 'r')):
date = datetime.datetime.strptime(row[1], '%Hh%M %d/%m/%Y')
desc = row[2]
obj = Event(date, desc)
if (today <= obj.dt <= today + margin):
event_tab.append(obj)
while not bot.is_closed:
for item in event_tab:
await bot.send_message(discord.Object(id=general_channel_id), "@everyone, look at this reminder !"
"You have a rendezvous planned at : " + item.str + "\n *" + item.desc + "*")
await asyncio.sleep(86400) # task will run every day - 86400 sec
#toDoDB = []
#def channelDBManager(channel):
# channelExists = False
# for db in toDoDB:
# if db[0] == channel:
# channelExists = True
# currentDB = db[1]
# if not channelExists:
# toDoDB.append([channel, []])
# for db in toDoDB:
# if db[0] == channel:
# currentDB = db[1]
# try:
# return currentDB
# except:
# print("channeldbmanager fatal fail - exiting")
# exit()
#def newToDo(desc, channel):
# db = channelDBManager(channel)
# status = True
# tempTodo = [desc, status]
# db.append(tempTodo)
#def doneToDo(id, channel):
# db = channelDBManager(channel)
# i = 0
# success = False
# for todo in db:
# i += 1
# if i == id:
# success = True
# tempI = i - 1
# db.remove(db[tempI])
# return success
#def listToDo(channel):
# db = channelDBManager(channel)
# id = 0
# returnList = []
# for todo in db:
# temptodo = []
# for i in todo:
# temptodo.append(i)
# id += 1
# temptodo.insert(0, id)
# returnList.append(temptodo)
# return returnList
#bot = discord.Client()
@bot.event
async def on_ready():
print('Logged in as')
print(bot.user.name)
print(bot.user.id)
print('------')
@bot.command()
async def ping(*args):
await bot.say(":ping_pong: Pong!")
#@bot.event
#async def on_message(message):
# channel = str(message.channel.id)
# command = str(message.content)
# if command.startswith("/"):
# print(toDoDB)
# if command.startswith("/add "):
# command = command.replace("/add ", "")
# if command == "":
# await bot.send_message(message.channel, ":x: No ToDo entered.")
# print(":x: No ToDo entered.")
# newToDo(command, channel)
# await bot.send_message(message.channel, ":white_check_mark: ToDo `" + command + "` added.")
# print(":white_check_mark: ToDo '" + command + "' added.")
# elif command == "/add":
# await bot.send_message(message.channel, ":x: Usage: `/add [TOD O]`")
# print(":x: Usage: `/add [TOD O]`")
# elif command == "/todo":
# list = listToDo(channel)
# printline = ""
# for todo in list:
# printline = printline + "**[" + str(todo[0]) + "]** - " + str(todo[1]) + "\n"
# if printline == "":
# printline = ":metal: **No ToDo's!** :metal:"
# else:
# printline = ":pencil: **ToDo's:** :pencil:\n\n" + printline
# await bot.send_message(message.channel, printline)
# print(printline)
# elif command.startswith("/done "):
# command = command.replace("/done ", "")
# try:
# command = int(command)
# except:
# await bot.send_message(message.channel, ':x: ID needs to be a number!')
# print(":x: ID needs to be a number!")
# return
# success = doneToDo(command, channel)
# if success:
# await bot.send_message(message.channel, ':white_check_mark: ToDo done.')
# print(":white_check_mark: ToDo deleted")
# else:
# await bot.send_message(message.channel, ':x: No ToDo with ID **' + str(command) + '**')
# print(':x: No ToDo with ID **' + str(command) + '**')
# elif command == "/done":
# await bot.send_message(message.channel, ":x: Usage: `/done [ID]`")
# print(":x: Usage: `/done [ID]`")
# elif command == "/help":
# printline = "'/todo' - Show the current todo list.\n'/add [TOD O]' - Add a new todo.\n'/done [ID]' - Mark a todo done (delete).\n'/help' - Show this menu.\nv1.0 by @xdavidhu"
# printline = ":question: **Help menu:** :question:\n" + "```" + printline + "```"
# await bot.send_message(message.channel, printline)
# print(printline)
# elif command.startswith("/"):
# printline = ":x: Command `" + command + "` not found. Type `/help` for the help menu."
# await bot.send_message(message.channel, printline)
# print(printline)
#@bot.command()
#async def new_rdv(*args):
# #i = -1
# d = datetime.datetime.strptime(' '.join(args), '%H:%M %d/%m/%Y')
# e = Event(d, "No description was given to this event.")
# num_lines = sum(1 for line in open('dates'))
# with open('dates', 'a') as file:
# file.write(str(num_lines) + ": " + e.str + ' *' + e.desc + '*\n')
# await bot.say("New Rendezvous is set at : " + e.str + "\n \"" + e.desc + "\"")
# file.close()
@bot.command(aliases=['add_rdv'])
async def new_rdv(*args):
seq = (args[0], args[1])
line_count = sum(1 for line in open('dates.csv'))
try:
d = (datetime.datetime.strptime(' '.join(seq), '%H:%M %d/%m/%Y'))
with open('dates.csv', 'a', newline='') as csvfile:
spamwriter = csv.writer(csvfile)
if len(args)>2:
spamwriter.writerow([str(line_count)] + [d.strftime("%Hh%M %d/%m/%Y")] + [args[2]])
else:
spamwriter.writerow([str(line_count)] + [d.strftime("%Hh%M %d/%m/%Y")] + ["No description was given for this Rendezvous"])
await bot.say("The new Rendezvous was correctly added to the list.\n")
csvfile.close()
except ValueError:
await bot.say("Error: The date format you entered is invalid\n")
@bot.command(aliases=['modify_rdv'])
async def mod_rdv():
await bot.say("lol")
@bot.command(aliases=['list_rdv', 'all_rdv', 'see_rdv', 'look_rdv'])
async def check_rdv():
with open('dates.csv', 'r') as liste_rdv, open('temp.txt', 'a') as tempf:
liste_csv = csv.reader(liste_rdv)
for row in liste_csv:
tempf.write("ID: " + row[0] + " | Date: " + row[1] + " | Description: " + row[2] + "\n")
tempf.close()
with open('temp.txt', 'r') as tempf:
await bot.say(tempf.read())
os.remove('temp.txt')
liste_rdv.close()
@bot.command(aliases=['delete_rdv', 'remove_rdv'])
async def del_rdv(*args):
line_nbr = int(args[0])
max_line = sum(1 for line in open('dates.csv'))
await bot.say("Deleting Rendezvous number " + args[0] + "\n...\n")
if line_nbr >= max_line:
await bot.say("There is no Rendezvous with this ID. Use /check_rdv to see the list of Rendezvous and their ID\n")
return
with open("dates.csv", "r") as inp, open ("new.csv", "w", newline='') as out:
old_csv = csv.reader(inp)
new_csv = csv.writer(out)
line_list = list(old_csv)
del line_list[line_nbr]
x = 0
while x < (max_line - 1):
line_list[x][0] = str(x)
x = x + 1
new_csv.writerows(line_list)
os.remove('dates.csv')
os.rename('new.csv' ,'dates.csv')
inp.close()
out.close()
await bot.say("Done !\n")
@bot.command()
async def time():
k = 0
Paris = datetime.datetime.now()
Tomsk = Paris + datetime.timedelta(hours=6)
Xian = Paris + datetime.timedelta(hours=7)
Incheon = Paris + datetime.timedelta(hours=8)
tab = [Paris, Tomsk, Xian, Incheon]
tab2 = ["Paris", "Tomsk", "Xian", "Incheon"]
while (k <= 3):
if (tab2[k] == "Paris"):
tmp = tab[k].strftime("Paris / Bruxelles / Hot / Stockholm: %Hh %Mm %Ss")
else:
tmp = tab[k].strftime(tab2[k] + ": %Hh %Mm %Ss")
k += 1
await bot.say(tmp)
@bot.command(aliases=['h', 'help', 'commands', 'man', 'info'])
async def help_rdv():
await bot.say("Usage :\n"
"To add a new Rendezvous: .new_rdv H:M d/m/Y \"Description of the event\"\n"
"To delete a Rendezvous: .del_rdv ID\n"
#"To modify a Rendezvous: .mod_rdv ID \n"
"To check the list of Rendezvous: .check_rdv\n"
"To see this list of commands: .help_rdv\n"
"To see the different timezones of each member: .time\n")
bot.loop.create_task(check_event())
bot.run(token)
#await bot.change_presence(game=discord.Game(name='Nebula'))