· 5 years ago · Dec 20, 2020, 12:48 AM
1import random
2from discord.ext import commands
3from config import BOT
4import discord
5from discord.utils import get
6
7intents = discord.Intents.all()
8initial_extensions = ['cogs.cogs']
9token = BOT['TOKEN']
10bot = commands.Bot(command_prefix=BOT['PREFIX'], intents=intents)
11
12
13@bot.event
14async def on_ready():
15 await bot.change_presence(activity=discord.Game("Hypixel"))
16
17# Auto Join Role
18
19@bot.event
20async def on_member_join(member):
21 role = get(member.guild.roles, name='Unverified')
22 await member.add_roles(role)
23
24
25# fun stuff
26@bot.event
27async def on_message(message):
28 # hypixel ez copypastas
29 ez = ["ez"]
30 copypastas = ["Hello everyone! I'm an innocent who loves everything Hypixel.", "Your personality shines brighter than the sun.", "I had something to say, then I forgot it.", "Your Clicks per second are godly.", "Why can't Ender Dragon read a book? Because he always starts at the End.", "In my free time I like to watch cat videos on youtube", "Wait... This isn't what I typed!", "I like Minecraft pvp but you are truly better than me!", "I like pineapple on my pizza", "Blue is greener than purple for sure", "Let's be friends instead of fighting okay?", "Sometimes I sing soppy love songs in the car.", "I like to eat pasta, do you prefer nachos?", "I love the way your hair glistens in the light", "ILY<3", "You are very good at this game friend.", "When nothing is going right, go left.", "Anybody else really like Rick Astley?", "If the world in Minecraft is infinite....how can the sun revolve around it?", "I sometimes try to say bad things and then this happens :(", " I heard you like minecraft, so I built a computer so you can minecraft, while minecrafting in your minecraft.", "What happens if I add chocolate milk to macaroni and cheese?", "You're a great person! Do you want to play some Hypixel games with me?", "Pls give me doggo memes!", "I enjoy long walks on the beach and playing Hypixel", "I have really enjoyed playing with you! <3", "Please go easy on me, this is my first game!", "Doin a bamboozle fren.", "Behold, the great and powerful, my magnificent and almighty nemisis!", "When I saw the guy with a potion I knew there was trouble brewing.", "Maybe we can have a rematch?", "Can you paint with all the colors of the wind", "I need help, teach me how to play!", "Hey Helper, how play game?"]
31 for trigger in ez:
32 if message.content.count(trigger) > 0:
33 await message.channel.send(random.choice(copypastas))
34 # furry
35 if message.content.startswith('furry'):
36 await message.channel.send('UwU')
37 if message.content.startswith('furless'):
38 await message.channel.send('∩ʍ∩')
39 if message.content.startswith('yeet'):
40 await message.channel.send('yaaa!')
41 if message.content.startswith(':fingerspin:'):
42 await message.channel.send(file=discord.File('fingerspin.gif'))
43 await bot.process_commands(message)
44
45
46# report command
47@bot.command()
48@commands.cooldown(1, 43200, commands.BucketType.user)
49async def report(ctx, user, *, reason):
50 if ctx.channel.id == 730496513255669881:
51 # user side
52 embed = discord.Embed(title="Your Guild Report has Been Submitted!", color=0xb92d5d)
53 embed.add_field(name="You Reported: " + user, value="Report Reason: " + reason, inline=True)
54 embed.set_footer(text="You will be contacted about your report within 24 hours")
55 await ctx.author.send(embed=embed)
56
57 # staff side
58 staffembed = discord.Embed(title="A Report has Been Submitted!", color=0xb51a00)
59 staffembed.add_field(name="Reporter", value=ctx.author.display_name, inline=True)
60 staffembed.add_field(name="Reported Player/Users", value=user, inline=True)
61 staffembed.add_field(name="Report Reason:", value=reason, inline=False)
62 staffembed.set_footer(text="Create a ticket with the reporter by doing: '$new (@user) (reason)' in #staff-bot-commands")
63 staffrole = get(ctx.guild.roles, name='Guild Staff')
64 modrole = get(ctx.guild.roles, name='Discord Mod')
65 reportchannel = ctx.guild.system_channel
66 await reportchannel.send(embed=staffembed)
67 await reportchannel.send(f'{staffrole.mention} {modrole.mention}')
68
69
70
71# report command errors
72@report.error
73async def report_error(ctx, error):
74 if ctx.channel.id == 734256819089702922:
75 if isinstance(error, commands.MissingRequiredArgument):
76 if error.param.name == 'user' or 'reason':
77 embed = discord.Embed(title="Insufficient Arguments!", color=0xb92d5d)
78 embed.set_footer(text="Please use !report (player/user) (reason)")
79 await ctx.author.send(embed=embed)
80 await ctx.command.reset_cooldown(ctx)
81 if isinstance(error, commands.CommandOnCooldown):
82 embed = discord.Embed(title="Your on a Command Cooldown", color=0xb92d5d)
83 embed.set_footer(text="There is a 12 hour cooldown for using this command, and it isn't over yet!")
84 await ctx.author.send(embed=embed)
85
86@bot.command()
87@commands.has_role("Guild Master")
88async def reportembed(ctx):
89 rembed = discord.Embed(title="Welcome to the Report Channel", color=0xff6250)
90 rembed.add_field(name="What is this channel for?", value="This channel is for you to report members of the guild who are breaking the rules!", inline=True)
91 rembed.add_field(name="You can report someone by doing", value="!report (player) (reason)", inline=False)
92 rembed.set_footer(text="There is a 12 hour cool down for using this command, please use it wisely.")
93 await ctx.channel.send(embed=rembed)
94
95
96
97@bot.command()
98@commands.has_role("Guild Master")
99async def rulesembed(ctx):
100 rembed = discord.Embed(title="Read and Agree to the Rules", color=0xb92d5d)
101 rembed.add_field(name="By checking the box below,", value="you agree and have read the guild rules and introduction page.", inline=False)
102 rembed.set_footer(text="React below")
103 await ctx.channel.send(embed=rembed)
104
105
106@bot.event
107async def on_raw_reaction_add(payload):
108 if payload.message_id == 741437491944358060:
109 if payload.emoji.name == '\N{WHITE HEAVY CHECK MARK}':
110 guild = await bot.fetch_guild(payload.guild_id)
111 if guild is not None:
112 member = payload.member
113 guild_member = discord.utils.get(guild.roles, name="Guild Member")
114 pending = discord.utils.get(guild.roles, name="Rules Pending")
115 await member.add_roles(guild_member)
116 await member.remove_roles(pending)
117 channel = bot.get_channel(payload.channel_id)
118 user = bot.get_user(payload.user_id)
119 message = await channel.fetch_message(payload.message_id)
120 emoji = payload.emoji.name
121 await message.remove_reaction(emoji, user)
122
123
124# cog import
125if __name__ == '__main__':
126 for extension in initial_extensions:
127 bot.load_extension(extension)
128
129
130## XP Mark Command ##
131
132## Hypixel API
133
134import aiohttp
135import requests
136import gspread
137from oauth2client.service_account import ServiceAccountCredentials
138
139# data = requests.get("https://api.hypixel.net/guild?key=fe921ab9-c74f-4a31-a9ef-dbaa13b8f854&name=Definite").json()
140
141@bot.command()
142@commands.has_role("Guild Staff")
143@commands.cooldown(1, 45, commands.BucketType.user)
144async def markgxp(ctx):
145 await ctx.channel.purge(limit=1)
146 embed = discord.Embed(title="You Have Marked the Weekly GXP", color=0x77bb40)
147 embed.set_author(name="View the Weekly GXP Document", url="https://shorturl.at/fzJ08")
148 embed.set_footer(text="This command has a 45 second cooldown!")
149 await ctx.author.send(embed=embed)
150 async with aiohttp.ClientSession() as session:
151 async with session.get("https://api.hypixel.net/guild?key=fe921ab9-c74f-4a31-a9ef-dbaa13b8f854&name=Definite") as resp:
152 data = await resp.json()
153 scores = {}
154 # For every guild member:
155 for count, member in enumerate(data['guild']['members']):
156 res = requests.get("https://playerdb.co/api/player/minecraft/" +
157 data['guild']['members'][count]['uuid']) # Response from server
158
159 if res.status_code != 200: # If it wasn't a success, continue the loop and print a message
160 print("Error 1: Invaild name from player database API!")
161 continue
162
163 # We know it was successful if we got to this point, so it's safe to try and get data from our response
164 name = res.json()['data']['player']['username']
165 # Members' GXP
166 xp = data['guild']['members'][count]['expHistory']
167
168 # to record score with the name using dict
169 scores[name] = sum(xp.values())
170
171 # Weekly Total
172 wTotal = sum(scores.values())
173
174
175
176 ## Google Sheets
177
178 scope = ["https://spreadsheets.google.com/feeds",'https://www.googleapis.com/auth/spreadsheets',"https://www.googleapis.com/auth/drive.file","https://www.googleapis.com/auth/drive"]
179 credbot = ServiceAccountCredentials.from_json_keyfile_name("credbot.json", scope)
180 client = gspread.authorize(credbot)
181 sheet = client.open("Definite Guild Daily XP").sheet1
182
183
184 usernames = []
185 values = []
186 ign = []
187
188 for i in range(3):
189 usernames.insert(0, [None])
190 values.insert(0, [None])
191
192 for key, value in scores.items():
193 usernames.append([key])
194 ign.append([key])
195 values.append([value])
196
197 # print(usernames)
198 # print(values)
199
200
201 sheet.update('B:B', usernames)
202 sheet.update('C:C', values)
203
204
205 lastRow = sheet.row_count
206 lastRow = lastRow
207
208 if sheet.append_row(['Total', wTotal]):
209 sheet.delete_rows(lastRow)
210 else:
211 print("Could not delete outdated 'Total' row!")
212
213@markgxp.error
214async def markgxp_error(ctx, error):
215 if isinstance(error, commands.CommandOnCooldown):
216 embed = discord.Embed(title="Your on a Command Cooldown", color=0xb92d5d)
217 embed.set_footer(text="There is a 45 second cooldown for using this command, and it isn't over yet!")
218 await ctx.author.send(embed=embed)
219 await ctx.channel.purge(limit=1)
220
221
222
223
224try:
225 bot.run(token)
226except:
227 pass
228
229
230
231
232
233# HOW TO GET ERRORS FROM FAILED COMMANDS #
234
235#@bot.event
236#async def on_command_error(ctx, exc):
237# etype = type(exc)
238# trace = exc.__traceback__
239# verbosity = 4
240# lines = traceback.format_exception(etype, exc, trace, verbosity)
241#
242# traceback_text = ''.join(lines)
243# await ctx.channel.send(traceback_text)
244