-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.py
More file actions
165 lines (141 loc) · 6.47 KB
/
bot.py
File metadata and controls
165 lines (141 loc) · 6.47 KB
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
#bot.py
#First created 2019-10-31
import os
import random
import discord
import logging
from discord.ext import commands, tasks
from dotenv import load_dotenv
import asyncio
import datetime
#Initializes required tokens from .env-file
load_dotenv()
TOKEN = os.getenv("DISCORD_TOKEN")
client = commands.Bot(command_prefix = ".") #Initialize client class
logging.basicConfig(level=logging.INFO) #Initialize logging and status printout
target_channel_id = 417402270188044291 #ID for meeting-information
#Prints BOTs status and connected guild at start
@client.event
async def on_ready():
guild = discord.utils.get(client.guilds)
print(
"------------------------------------------------------\n"
f"{client.user} is connected to the following guild(s):\n"
f"{guild.name} (id: {guild.id})"
"\n------------------------------------------------------"
)
@tasks.loop(hours=168.0)
async def called_every_week():
message_channel = client.get_channel(target_channel_id)
print(f"Acquired channel: {message_channel}")
await message_channel.send(f"Beep-Boop: Möte som idag i sal 318 kl. 15:00. Fika finns som vanligt. \n{discord.Guild.default_role}")
@called_every_week.before_loop
async def before():
print("Waiting for Wednesday 08:00 to start task loop...")
await client.wait_until_ready()
while datetime.datetime.now().strftime("%w") != "3":
await asyncio.sleep(43200)
while datetime.datetime.now().strftime("%H") != "08":
await asyncio.sleep(3600)
print("Finished waiting: Task loop starts")
called_every_week.start()
#When new member joins, sends them a direct-message on Dicord
@client.event
async def on_member_join(member):
await member.create_dm()
await member.dm_channel_send(f"Hej {member.name}, välkommen till NTI Johannebergs Programmeringsklubb!")
#When member leaves, print to console
#@client.event
#async def on_member_remove(member):
# print(f"{member} has left the server.")
# await member.create_dm()
# await member.dm_channel_send(f"Hej {member.name}, tråkigt att du lämnar oss")
def plus(content):
# find index of plus
pos = content.find("+")
if pos != -1: # if characters isnt found, find() returns -1
content = "".join(c for c in content if c.isdigit()) # remove all non ints from content
left_of = content[0:pos]
right_of = content[pos:len(content)]
print(left_of + right_of)
return int(left_of) + int(right_of)
#Commands and responses for client
@client.command(name="ping", help="Returns latency of Bot.")
async def ping(ctx):
await ctx.send(f"Pong! {round(client.latency * 1000)}ms")
@client.command(help="Repeats your message n times")
async def repeat(ctx, times: int, content='repeating...'):
#Repeats a message multiple times.
for i in range(times):
await ctx.send(f":clap:{content}:clap:")
@client.command(aliases = ["8ball"], help="The Magic 8 Ball has all the answers to life's questions.")
async def _8ball(ctx, *, question):
responses = [
"It is certain.",
"It is decidedly so.",
"Without a doubt.",
"Yes - definitely.",
"You may rely on it.",
"As I see it, yes.",
"Most likely.",
"Outlook good.",
"Yes.",
"Signs point to yes.",
"Reply hazy, try again.",
"Ask again later.",
"Better not tell you now.",
"Cannot predict now.",
"Concentrate and ask again.",
"Don't count on it.",
"My reply is no.",
"My sources say no.",
"Outlook not so good.",
"Very doubtful."]
await ctx.send(f"Question: {question}\nAnswer: {random.choice(responses)}")
@client.event
async def on_message(message):
#Checks if BOT sent the message to prevent infinite feedback-loop
if message.author == client.user:
return
programming_jokes = [
"How many programmers does it take to screw in a light bulb? \n\nNone. It's a hardware problem.",
"A programmer puts two glasses on his bedside table before going to sleep. A full one, in case he gets thirsty, and an empty one, in case he doesn’t.",
"Java and C were telling jokes. It was C's turn, so he writes something on the wall, points to it and says \"Do you get the reference?\" \nBut Java didn't.",
"There are 10 kinds of people in this world: Those who understand binary, those who don't, and those who weren't expecting a base 3 joke.",
"A programmer is heading out to the grocery store, so his wife tells him \"get a gallon of milk, and if they have eggs, get a dozen.\" He returns with 13 gallons of milk.",
"What's the best thing thing about UDP jokes? \n\nI don't care if you get them",
"What's the best part about TCP jokes? \n\nI get to keep telling them until you get them.",
"Your mama's so FAT she can't save files bigger than 4GB.",
"In order to understand recursion you must first understand recursion."
]
#Checks the message contains and responds accordingly
for msg in ["i am", "im", "i'm", "jag är"]: #Dadjoke
if msg in message.content.lower():
response = message.content.lower().split()
msg_out = response[response.index(msg.split()[-1]) +1]
await message.channel.send(f"Hej {msg_out}, jag är {client.user}")
if message.content == "joke":
response = random.choice(programming_jokes)
await message.channel.send("Did someone say joke? \n" + response)
elif message.content == "dm":
await message.author.send("Test123")
elif message.content == "Hello":
await message.channel.send(f"Hello dear {message.author.nick} at {message.guild}, I see you joined {message.author.joined_at}.")
elif "+" in message.content:
await message.channel.send(plus(message.content))
await client.process_commands(message) #Enables commands
@commands.guild_only()
@client.command(name="clear")
async def clear(ctx, amount=1):
role = discord.utils.get(ctx.guild.roles, name="styrelseledamöter")
if role in ctx.author.roles:
await ctx.channel.purge(limit=amount+1)
else:
await ctx.send(f"{ctx.author} doesn't have permission")
#Advanced logging
#logger = logging.getLogger("discord")
#logger.setLevel(logging.DEBUG)
#handler = logging.FileHandler(filename="discord.log", encoding="utf-8", mode="w")
#handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
#logger.addHandler(handler)
client.run(TOKEN) #Actually starts and runs the BOT