Skip to content

Instantly share code, notes, and snippets.

@xCirno1
Last active March 11, 2021 01:38
Show Gist options
  • Save xCirno1/7aeff9c265326a859015fe49a69488c1 to your computer and use it in GitHub Desktop.
Save xCirno1/7aeff9c265326a859015fe49a69488c1 to your computer and use it in GitHub Desktop.
import discord
from discord.ext import commands
import datetime
import time
import re
import wikipedia
from urllib import parse, request
import random
import os
from keep_alive import keep_alive
from discord.utils import get
from google_trans_new import google_translator, LANGUAGES
import math
import akinator
import asyncio
from AntiSpam import AntiSpamHandler
from better_profanity import profanity
from searchgoogle import search
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
from response import conversation
from operator import pow, truediv, mul, add, sub
from kbbi import KBBI
from kbbi import TidakDitemukan
from bahasa import *
intents = discord.Intents.default()
intents.members = True
chatbot = ChatBot("Miku", silence_performance_warning=True,storage_adapter="chatterbot.storage.SQLStorageAdapter")
trainer = ListTrainer(chatbot.storage)
profanity.load_censor_words_from_file("badwords.txt")
aki = akinator.Akinator()
translator = google_translator()
client = discord.Client()
bot = commands.Bot(command_prefix=['m!', 'M!'], intents=intents)
bot.remove_command('help')
suggestions = []
spamm = AntiSpamHandler(bot)
welcome_message_appeal = []
pfstatusdict = []
pfstatus = 'on'
pfstatusq = 'off'
@bot.group(invoke_without_command = True)
async def help(ctx):
embed = discord.Embed(title="Bot Commands",description="Here are all list of current bot commands!", color=0x0000FF)
embed.add_field(name="Moderation", value="kick ban unban\nmute unmute nick\n purge")
embed.add_field(name="Misc", value="ping suggest")
embed.add_field(name="Information", value="farm info version \n createdate")
embed.add_field(name="Fun", value="neko flip rnumber\n talk train")
embed.add_field(name="Math", value="math pythagoras")
embed.add_field(name="Search", value="google youtube wiki\n kbbi")
await ctx.send(embed = embed)
@bot.command()
async def me(ctx):
embed = discord.Embed(title="About Me", description='''Nakano Miku''', color=0x6b94ff)
embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/764033250749579284/817978651965652992/mBlacofDyY7-0vQBYQyCwZgiRpkiKDVjZEJeB2u9IQxBvvlsBFz5KiYqEoRH75OPhjYw300.png")
embed.set_image(url="https://cdn.discordapp.com/attachments/764033250749579284/817981641125265418/Untitled29_20210307114647.png")
await ctx.send(embed = embed)
@bot.command()
async def ping(ctx):
pingBefore = time.time()
pongMessage = await ctx.send('pong')
pong = time.time() - pingBefore
pong = pong * 1000
pong = round(pong, 2)
if(pong > 1000):
await pongMessage.edit(content='Latency: ' + str(pong) + 'ms\n **We are aware that our server might have high latency.** Please contact <@650447110402998302> in dm.')
print(f"RuntimeWarning: ConnectionDelayed: {pong}ms in {ctx.message.id}.")
else:
await pongMessage.edit(content='Latency: '+str(pong) + 'ms\n**No lag at all!**')
@bot.command(name="math")
async def _math(ctx, *, problem):
problem = problem.replace(' ', '')
operators = {
'+': add,
'-': sub,
'*': mul,
'/': truediv,
'^': pow
}
def calculate(s):
if s.isdigit():
return float(s)
for c in operators.keys():
left, operator, right = s.partition(c)
if operator in operators:
return operators[operator](calculate(left), calculate(right))
await ctx.send(str(calculate(problem)))
@bot.command()
async def info(ctx):
embed = discord.Embed(title=f"{ctx.guild.name}",
timestamp=datetime.datetime.utcnow(), color=discord.Color.blue())
embed.add_field(name="Server created at", value=f"{ctx.guild.created_at}")
embed.add_field(name="Server Owner", value=f"{ctx.guild.owner.mention}")
embed.add_field(name="Server Region", value=f"{ctx.guild.region}")
embed.add_field(name="Server ID", value=f"{ctx.guild.id}")
embed.add_field(name="Member Count", value=f"{len(ctx.guild.members)}")
embed.add_field(name="Role Count", value=f"{str(len(ctx.guild.roles))}")
embed.set_thumbnail(url=f"{ctx.guild.icon_url}")
await ctx.send(embed=embed)
@bot.command(aliases=['yt', 'watch'])
async def youtube(ctx, *, search):
firstPing = time.time()
query_string = parse.urlencode({'search_query': search})
html_content = request.urlopen('http://www.youtube.com/results?' + query_string)
search_results = re.findall(r'/watch\?v=(.{11})', html_content.read().decode())
print(search_results)
print(ctx.author)
await ctx.send(f'https://www.youtube.com/watch?v={search_results[0]}\n ({round(time.time() - firstPing, 2)}s)')
@bot.command()
@commands.has_permissions(ban_members = True)
async def ban(ctx, member : discord.Member, *, reason = None):
await member.ban(reason = reason)
await ctx.send(member + 'has been banned!')
@bot.command()
@commands.has_permissions(ban_members = True)
async def unban(ctx, id: int):
user = await bot.fetch_user(id)
await ctx.guild.unban(user)
@bot.command()
@commands.has_permissions(kick_members = True)
async def kick(ctx, member : discord.Member):
await bot.kick(member)
@bot.command(pass_context=True)
@commands.has_permissions(kick_members = True)
async def mute(ctx, member: discord.Member):
if get(ctx.guild.roles, name="MUTED"):
role = discord.utils.get(ctx.guild.roles, name="MUTED")
await member.add_roles(role)
await ctx.send(f"{member} has been muted!")
elif(role in member.roles):
await ctx.send(f"Hey, chill down {member} is still muted! Give them a break at least...")
else:
guild=ctx.guild
perms = discord.Permissions(send_messages=False, read_messages=True)
role = await guild.create_role(name="MUTED", permissions=perms)
role.hoist=True
await member.add_roles(role)
await ctx.send(f"{member} has been muted! And created new role ```MUTED```")
@bot.command(pass_context=True)
@commands.has_permissions(kick_members = True)
async def unmute(ctx, member: discord.Member = None):
role = discord.utils.get(ctx.guild.roles, name="MUTED")
await member.remove_roles(role)
await ctx.send(f"{member} has been unmuted!")
@bot.command()
async def farm(ctx):
embed = discord.Embed(title="Farming prices :", description="Here are all farming price based on speed and location!", color=0x0000FF)
embed.add_field(name="Slow Order :", value="Loc 01 - 45: 100g/card", inline=False)
embed.add_field(name="Normal Order :", value="Loc 45 - max: 115g/card\nLoc 45 - max: 115g/card", inline=False)
embed.add_field(name="Fast Order :", value="Loc 01 - 45: 136g/card\nLoc 45 - max: 115g/card ", inline=False)
await ctx.send(embed=embed)
@bot.command(aliases=['appeal', 'settings', 'setting'])
@commands.has_permissions(manage_guild = True)
async def suggest(ctx):
embed = discord.Embed(title='Hello!', description="**Welcome to server settings! \n**Please take a look of what do you want to set / change.\n A. Welcome message to server\n B. Profanity filter (Badword filter) [enabled by default]\n C. Spam filter\n D. Others", color=0x0000FF)
suggestEmbed = await ctx.send(embed=embed)
waitAppeal = await bot.wait_for('message', timeout=30, check=lambda message: message.author==ctx.author and message.channel==ctx.channel)
if(waitAppeal.content.lower() == 'a'):
await suggestEmbed.delete()
embed = discord.Embed(title='alright welcome message!', description="**Where do you want to set your welcome message?** \n Enter the channel tag! \n\n***__NOTE: THIS METHOD CANNOT BE REDO, UNLESS CONTACT OUR DEVELOPER!__***", color=0x0000FF)
await ctx.send(embed=embed)
wmAppeal = await bot.wait_for('message', timeout=30, check=lambda message: len(message.channel_mentions) != 0 and message.channel == ctx.channel and ctx.author == message.author)
channel_id = wmAppeal.channel_mentions[0].id
channel_id = str(channel_id)
fr = open("welcomeMessageData.txt", "r")
fr = fr.read()
if channel_id not in fr:
f = open("welcomeMessageData.txt", "a")
f.write(str(ctx.guild.id) + '\n')
f.write(channel_id + '\n')
f.write('None' + '\n')
f.write('Welcome!' + '\n')
f.write('None' + '\n')
f.write('#0000FF' + '\n')
f.write('None' + '\n')
f.write('None' + '\n')
f.close()
embed = discord.Embed(title="Success!", description="Welcome message has been applied to this server!", color = 0x0000FF)
await ctx.send(embed=embed)
else:
await ctx.send('Your server has already had welcome message system!')
elif(waitAppeal.content.lower() == 'b'):
await suggestEmbed.delete()
if(ctx.message.id in pfstatusdict):
pfstatus = 'off'
else:
pfstatus = 'on'
embed = discord.Embed(title='alright profanity filter!', description=f'Current profanity filter is: {pfstatus}. Do you want to set it to {pfstatusq}(Type: yes/no)', color=0x0000FF)
await ctx.send(embed=embed)
waitPf = await bot.wait_for('message', timeout=30, check=lambda message: message.author==ctx.author and message.channel==ctx.channel)
if(waitPf == 'yes' and pfstatusq == 'on'):
return
elif(waitAppeal.content.lower() == 'd'):
await suggestEmbed.delete()
waitSuggestion = await bot.wait_for('message', timeout=30, check=lambda message: message.author==ctx.author and message.channel==ctx.channel)
if(not profanity.contains_profanity(waitSuggestion)):
await waitSuggestion.add_reaction('✅')
embed = discord.Embed(title='Success!', description=f'Thank you for your suggestion! Here is your suggestion ```{waitSuggestion}```\n ~ {ctx.author}', color=0x0000FF)
await ctx.send(embed=embed)
suggestions.append(waitSuggestion)
print(suggestions)
elif(profanity.contains_profanity(waitSuggestion)):
await waitSuggestion.add_reaction('❌')
embed = discord.Embed(title='Failed!', description='Our system has detected profanity content in your suggestion. Contact Flamee#1175 if you think this is wrong.', color=0x0000FF)
await ctx.send(embed=embed)
elif('nothing' in waitSuggestion.lower()):
await waitSuggestion.add_reaction('❌')
embed = discord.Embed(title='Failed!', description=f'Please enter a valid suggestion not {waitSuggestion}. Contact Flamee#1175 if you think this is wrong.', color=0x0000FF)
await ctx.send(embed=embed)
@bot.command(aliases=['wikipedia'])
async def wiki(ctx, * , word):
wordSplit = word.split()
lc = wordSplit[0]
if lc in LANGUAGES:
wikipedia.set_lang(lc)
else:
wikipedia.set_lang("en")
try:
page = wikipedia.page(word).title
if(page != word):
definition = wikipedia.summary(word, sentences=4)
await ctx.send(f"Word not found, closest word: **{page}\n**{definition}")
else:
definition = wikipedia.summary(word, sentences=4)
await ctx.send(f"Word: **{page}\n**{definition}")
except wikipedia.DisambiguationError as results:
try:
select = random.choice(results.options)
page = str(wikipedia.page(select))
page = page.replace("<WikipediaPage '" , "")
page = page.replace("'>", "")
definition = wikipedia.summary(select, sentences=4)
await ctx.send(f"There are to many results, we picked 1 for you: **{page}**\n{definition}")
except wikipedia.PageError:
await ctx.send(f'We have found a result to {word}, but has no content in the wikipedia page!')
except wikipedia.PageError:
await ctx.send('No definition found!')
print(word)
print(ctx.author)
@bot.command()
async def neko(ctx):
path=['Neko.jpg', 'Neko1.jpg', 'Neko2.jpg', 'Neko3.jpg', 'Neko4.jpg', 'Neko5.jpg','Neko6.jpg','Neko7.jpg','Neko8.jpg','Neko9.jpg','Neko10.jpg','Neko11.jpg','Neko12.jpg','Neko13.jpg', 'neko14.jpg', 'neko15.jpg', 'neko16.jpg', 'neko18.jpg', 'neko19.jpg' ]
d=random.choice(path)
await ctx.send('Nyaa~')
await ctx.send(file=discord.File(d))
@bot.command(pass_context=True)
async def nick(ctx, member: discord.Member, *, changeName):
try:
await member.edit(nick=changeName)
await ctx.send(f'Nickname changed for {member} to: ' + changeName)
except discord.Forbidden:
fh = 0
embed = discord.Embed(title='Error!', description=f"**It seems that we are getting an error, possible error source: **\n 1. I don't have permission to change nickname\n 2. My role is lower than {member}", color = 0x0000ff)
this = await ctx.send(embed=embed)
while fh < 4:
fh += 1
embed2 = discord.Embed(title='Error!', description=f"**It seems that we are getting an error, possible error source: **\n 1. I don't have permission to change nickname\n 2. My role is lower than {member}", color = 0x800080)
await this.edit(embed=embed2)
await asyncio.sleep(1)
embed3 = discord.Embed(title='Error!', description=f"**It seems that we are getting an error, possible error source: **\n 1. I don't have permission to change nickname\n 2. My role is lower than {member}", color = 0x000000)
await this.edit(embed=embed3)
await asyncio.sleep(1)
embed4 = discord.Embed(title='Error!', description=f"**It seems that we are getting an error, possible error source: **\n 1. I don't have permission to change nickname\n 2. My role is lower than {member}", color = 0x808080)
await this.edit(embed=embed4)
await asyncio.sleep(1)
embed5 = discord.Embed(title='Error!', description=f"**It seems that we are getting an error, possible error source: **\n 1. I don't have permission to change nickname\n 2. My role is lower than {member}", color = 0xffffff)
await this.edit(embed=embed5)
await asyncio.sleep(1)
embed6 = discord.Embed(title='Error!', description=f"**It seems that we are getting an error, possible error source: **\n 1. I don't have permission to change nickname\n 2. My role is lower than {member}", color = 0xffff00)
await this.edit(embed=embed6)
await asyncio.sleep(1)
embed7 = discord.Embed(title='Error!', description=f"**It seems that we are getting an error, possible error source: **\n 1. I don't have permission to change nickname\n 2. My role is lower than {member}", color = 0xff0000)
await this.edit(embed=embed7)
await asyncio.sleep(1)
@bot.command()
async def flip(ctx):
flips = ['Head', 'Tails']
flip = random.choice(flips)
await ctx.send(f'{flip}!')
@bot.command(name="purge")
@commands.has_permissions(manage_messages = True)
async def _purges(ctx, limits: int):
await ctx.channel.purge(limit=limits)
embeds = discord.Embed(color=0x0000FF)
embeds.add_field(name="Success!", value=f"Purged {str(limits)} messages!")
await ctx.send(embed=embeds)
@bot.command(aliases=['av'])
async def avatar(ctx, * ,member: discord.Member=None):
try:
userAvatar = member.avatar_url
embed = discord.Embed(color=0x0000FF)
embed.add_field(name='Avatar', value=f"{member}'s avatar!")
embed.set_image(url = userAvatar)
await ctx.send(embed=embed)
except AttributeError:
userAvatar = ctx.author.avatar_url
embed = discord.Embed(color=0x0000FF)
embed.add_field(name='Avatar', value=f"{ctx.author}'s avatar!")
embed.set_image(url = userAvatar)
await ctx.send(embed=embed)
@bot.command(aliases=['rnumber', 'rnum'])
async def randomnumber(ctx, Min: int, Max: int):
await ctx.send(f'Here is your number between {Min} to {Max}: {random.randint(Min, Max)}')
@bot.command(aliases=['trans', 'tr'])
async def translate(ctx,lang, *, word):
if(lang in LANGUAGES):
result = translator.translate(word,lang_tgt=lang)
else:
result = translator.translate(lang+word,lang_tgt="en")
await ctx.send(result)
@bot.command()
async def choose(ctx, *, args):
args = args.split(',')
await ctx.send(f'{random.choice(args)}')
@bot.command(aliases=['pyth'])
async def pythagoras(ctx, format,*, sides):
if(format == "re"):
result = sides.split(',')
if(int(result[0])>int(result[1])):
answer = math.sqrt(int(result[0])**2 - int(result[1])**2)
await ctx.send(f"answer:{answer} \na^2 + b^2 = c^2 \n a^2 + {int(result[1])}^2 = {int(result[0])}^2 \n a^2 = {int(result[0])**2-int(result[1])**2}\n **a = {answer}**")
else:
answer = math.sqrt(int(result[1])**2 - int(result[0])**2)
await ctx.send(f"answer:{answer} \na^2 + b^2 = c^2 \n a^2 + {int(result[0])}^2 = {int(result[1])}^2 \n a^2 = {int(result[1])**2-int(result[0])**2}\n **a = {answer}**")
else:
result = sides.split(',')
answer = math.sqrt(int(result[0])**2 + int(result[1])**2)
await ctx.send(f"answer:{answer} \na^2 + b^2 = c^2 \n {int(result[0])}^2 + {int(result[1])}^2 = c^2 \n {int(result[0])**2+int(result[1])**2} = c^2\n **c = {answer}**")
@bot.command()
async def version(ctx):
page1 = discord.Embed (
title = 'Version: 1.0.0',
description = '- Initial release \n - Added several commands',
colour = discord.Colour.orange()
)
page2 = discord.Embed (
title = 'Version: 1.0.1',
description = '- Added Profanity filter \n - Added anti-spam feature \n - Added new section: Math \n - Improved wikipedia',
colour = discord.Colour.orange()
)
page3 = discord.Embed (
title = 'Version 1.0.2',
description = '- Added new command(s): version \n - Improved translate & added more languages \n - Bug fixed where every commands comes doubled \n - Removed anti spam feature (will come in the future)',
colour = discord.Colour.orange()
)
page4 = discord.Embed (
title = 'Version 1.0.3',
description = '- Added new section: search \n - Added new command(s): createdate \n - Added new response when called \n - Added search spam detection\n - Fixed version command where reactions wont load\n - Fixed problem where uppercase prefix are not counted \n - Released ai bot (beta)',
color = discord.Colour.orange())
page5 = discord.Embed(
title = 'Version 1.0.4',
description = '- Fixed ai chat bot where responded slowly\n - Added train command to train ai bot\n - Fixed mute command where only works in some servers\n- updated muted conditions\n - Improved math command\n - Added reaction to accepted suggestion in suggest command', color = discord.Colour.orange())
page6 = discord.Embed(
title = 'Version 1.0.5',
description = "- Added profanity filter to settings\n- Added current version and page number in version commands\n- Added new command(s): kbbi, length\n- Removed Miku response when called\n- Improved settings command\n- Changed suggest command to settings\n- Added Miku's status website: https://stats.uptimerobot.com/rByyGsAP2Q/787219172\n- Fixed a bug where math command can't be used with space", color = discord.Colour.orange())
page7 = discord.Embed(
title = 'Version 1.0.6',
description = '- Improved wikipedia search\n - Added new command(s): circle - Improved profanity detection & added some new filters\n - Added self avatar\n - Fixed AI training error\n - Train commands now automatically trains the bot\n - Changes in wikipedia command format\n- Added search time to search section commands (except: wikipedia)', color = discord.Colour.orange())
page8 = discord.Embed(
title='Version 1.0.7 [current version]',
description="- Changed version command first page to newest version\n - Fixed a bug in server info command where server owner returning 'None'\n - Removed page number from version command\n - Added fully customizable welcome message\n - Removed some unimportant imports to speed up the bot\n - Added some more fields in server info command", color = discord.Colour.orange())
pages = [page1, page2, page3, page4, page5, page6, page7, page8]
message = await ctx.send(embed = page7)
await message.add_reaction('⏮')
await message.add_reaction('◀')
await message.add_reaction('▶')
await message.add_reaction('⏭')
def check(reaction, user):
return user == ctx.author
i = 7
reaction = None
while True:
if str(reaction) == '⏮':
i = 0
await message.edit(embed = pages[i])
elif str(reaction) == '◀':
if i > 0:
i -= 1
await message.edit(embed = pages[i])
elif str(reaction) == '▶':
if i < 7:
i += 1
await message.edit(embed = pages[i])
elif str(reaction) == '⏭':
i = 7
await message.edit(embed = pages[i])
try:
reaction, user = await bot.wait_for('reaction_add', timeout = 30.0, check = check)
await message.remove_reaction(reaction, user)
except:
break
await message.clear_reactions()
@bot.command(aliases=["createdat", "created"])
async def createdate(ctx, member: discord.Member):
userAge = member.created_at
await ctx.send(f"{member}'s account, created at: {userAge}")
@bot.command(name="google")
async def _google(ctx, *, args):
firstPing = time.time()
result = search(args, num_results=20)
await ctx.send(f'{result[1]}\n ({round(time.time() - firstPing, 2)}s)')
print(args)
print(ctx.author)
@bot.command()
async def talk(ctx, *, args):
trainer.train(conversation)
response = chatbot.get_response(args)
await ctx.send(response)
@bot.command(name="train")
async def _train(ctx):
embed = discord.Embed(title="Miku AI Train", description="Silahkan masukkan input anda!", color=0x0000FF)
embed.add_field(name='Keterangan:', value='1. Tidak boleh terdapat pelesetan/kata yang mengandung unsur kekerasan dan/atau unsur kasar.\n2. Usahakan jangan melebihi 25 karakter dan kurang dari 4 karakter.\n3. Setelah berhasil, input dan output akan disimpan ke database dan bisa digunakan.(Mungkin akan ada delay)')
await ctx.send(embed = embed)
trainInput = await bot.wait_for('message', timeout=30, check=lambda message: message.author==ctx.author and message.channel==ctx.channel)
if(len(trainInput.content) > 25):
embed = discord.Embed(title="Failed!", description="Usahakan jangan masukkan Input yang melebihi 25 karakter!", color=0x0000FF)
await ctx.send(embed = embed)
elif(len(trainInput.content) < 4):
embed = discord.Embed(title="Failed!", description="Usahakan jangan masukkan Input yang kurang dari 4 karakter!", color=0x0000FF)
await ctx.send(embed = embed)
if(profanity.contains_profanity(trainInput.content)):
embed = discord.Embed(title="Failed!", description="Hey, kata itu termasuk kata kasar/kekerasan! Jangan menggunakan kata itu lain kali.", color=0x0000FF)
await ctx.send(embed = embed)
if(not profanity.contains_profanity(trainInput.content) and len(trainInput.content) < 25 and len(trainInput.content) > 4):
embed = discord.Embed(title="Success!", description="Sekarang silahkan masukkan output anda!", color=0x0000FF)
await ctx.send(embed=embed)
trainOutput = await bot.wait_for('message', timeout=30, check=lambda message: message.author==ctx.author and message.channel==ctx.channel)
if(len(trainOutput.content) > 25):
embed = discord.Embed(title="Failed!", description="Usahakan jangan masukkan otput yang melebihi 25 karakter!", color=0x0000FF)
await ctx.send(embed = embed)
elif(len(trainOutput.content) < 4):
embed = discord.Embed(title="Failed!", description="Usahakan jangan masukkan output yang kurang dari 4 karakter!", color=0x0000FF)
await ctx.send(embed = embed)
if(profanity.contains_profanity(trainOutput.content)):
embed = discord.Embed(title="Failed!", description="Hey, kata itu termasuk kata kasar/kekerasan! Jangan menggunakan kata itu lain kali.", color=0x0000FF)
await ctx.send(embed = embed)
if(not profanity.contains_profanity(trainOutput.content) and len(trainOutput.content) < 25 and len(trainOutput.content) > 4 and not profanity.contains_profanity(trainInput.content) and len(trainInput.content) < 25 and len(trainInput.content) > 4):
conversation.append(trainInput.content)
conversation.append(trainOutput.content)
print(conversation)
embed = discord.Embed(title="Sucess!", description=f"{ctx.author}, dengan Input: \n ```{trainInput.content}``` dan Output: \n ```{trainOutput.content}``` berhasil ditambahkan!", color=0x0000FF)
await ctx.send(embed = embed)
@bot.command(name="kbbi")
async def _kbbi(ctx, *, word):
firstPing = time.time()
try:
aa = KBBI(word)
await ctx.send(f'{aa}\n**({round(time.time()-firstPing, 2)}s)**')
except TidakDitemukan:
await ctx.send(f'Kata {word} tidak ditemukan!')
@bot.command()
async def length(ctx, *, args):
await ctx.send(f'{len(args)} characters!')
@bot.command()
async def refresh(ctx):
print('refreshed!')
print("suggestions: ", suggestions)
print("profanity filter off: ", pfstatusdict)
print("train: ", conversation)
await ctx.send('refreshed!')
@bot.command()
async def circle(ctx, search):
if(search == 'area' or search == 'a'):
embed = discord.Embed(title="Radius value!", description='Input the circle radius!', color = 0x0000FF)
await ctx.send(embed=embed)
r = await bot.wait_for('message', timeout=30, check=lambda message: message.author==ctx.author and message.channel==ctx.channel)
if(int(r.content)**2 % 7 != 0):
answer = int(r.content)**2 * 3.14
await ctx.send(f'answer: {str(answer)}\na = π×r^2\na = 3.14×{str(r.content)}^2\na = 3.14×{str(int(r.content)**2)}\n**a = {str(answer)}**')
elif(int(r.content)**2 % 7 == 0):
answer = int(r.content)**2/7 * 22
await ctx.send(f'answer: {str(answer)}\na = π×r^2\na = 22/7×{str(r.content)}^2\na = 22×{str(int(r.content)**2/7)}\n**a = {str(answer)}**')
elif(search == 'perimeter' or search == 'p'):
embed = discord.Embed(title="Radius value!", description='Input the circle radius!', color = 0x0000FF)
await ctx.send(embed=embed)
r = await bot.wait_for('message', timeout=30, check=lambda message: message.author==ctx.author and message.channel==ctx.channel)
if(int(r.content) % 7 != 0):
answer = int(r.content) * 6.18
await ctx.send(f'answer: {str(answer)}\na = 2×π×r\na = 2×3.14×{str(r.content)}\na = 3.14×{str(int(r.content)*2)}\n**a = {str(answer)}**')
elif(int(r.content) % 7 == 0):
answer = int(r.content) * 2 / 7 * 22
await ctx.send(f'answer: {str(answer)}\na = 2×π×r\na = 2×22/7×{str(r.content)}\na = 22×{str(int(r.content)/7)}\n = 22×{str(int(r.content)/7*2)}\n**a = {str(answer)}**')
elif(search == 'radius' or search == 'r'):
embed = discord.Embed(title="Radius value!", description='Input the circle radius!', color = 0x0000FF)
await ctx.send(embed=embed)
r = await bot.wait_for('message', timeout=30, check=lambda message: message.author==ctx.author and message.channel==ctx.channel)
@bot.command()
@commands.has_permissions(manage_guild = True)
async def welcome(ctx):
gi = ctx.guild.id
with open("welcomeMessageData.txt", mode="r+") as file:
lines = [line.rstrip() for line in file.readlines()]
if(str(gi) in lines):
with open("welcomeMessageData.txt") as myFile:
for num, line in enumerate(myFile, 1):
if str(gi) in line:
break
nwi = lines.index(str(gi))
nw = lines[nwi + 1] #channel
nt = lines[nwi + 2] #normal text
wt = lines[nwi + 3] #embed title
wd = lines[nwi + 4] #embed description
wc = lines[nwi + 5] #embed color
wh = lines[nwi + 6] #embed thumbnail
wi = lines[nwi + 7] #embed image
myFile = open('welcomeMessageData.txt', 'r')
if str(ctx.guild.id) in lines:
embed = discord.Embed(title='Welcome message settings!', description=f"**All of your current welcome message settings are shown below.**!\n A. Channel: **<#{nw}>**\n B. Text: **{nt}**\n C. Title: **{wt}**\n D. Description: **{wd}** \n E. Color: **{wc}** \n F. Thumbnail: **{wh}**\n G. Image: **{wi}**", color=0x00FFFF)
await ctx.send(embed = embed)
setText = await bot.wait_for('message', timeout=30, check=lambda message: message.channel == ctx.channel and ctx.author == message.author)
if(setText.content.lower() == 'channel' or setText.content.lower() == 'a'):
await ctx.send("Please enter the welcome message channel by tagging the channel!")
stc = await bot.wait_for('message', timeout=60, check=lambda message: message.channel == ctx.channel and ctx.author == message.author)
stc = stc.content.replace('\n', '<br>')
a_file = open("welcomeMessageData.txt", "r")
list_of_lines = a_file.readlines()
list_of_lines[num] = stc + '\n'
a_file = open("welcomeMessageData.txt", "w")
a_file.writelines(list_of_lines)
a_file.close()
embed = discord.Embed(title='Success!', description=f'Channel has been changed to {stc}!')
await ctx.send(embed = embed)
if(setText.content.lower() == 'text' or setText.content.lower() == 'b'):
await ctx.send("Please enter the text for welcome message! (type: `None` for none)")
stc = await bot.wait_for('message', timeout=60, check=lambda message: message.channel == ctx.channel and ctx.author == message.author)
stc = stc.content.replace('\n', '<br>')
a_file = open("welcomeMessageData.txt", "r")
list_of_lines = a_file.readlines()
list_of_lines[num + 1] = stc + '\n'
a_file = open("welcomeMessageData.txt", "w")
a_file.writelines(list_of_lines)
a_file.close()
embed = discord.Embed(title='Success!', description=f'Text has been changed to {stc}!')
await ctx.send(embed = embed)
if(setText.content.lower() == 'title' or setText.content.lower() == 'c'):
await ctx.send("Please enter the title for welcome message! (type: `None` for none)")
st = await bot.wait_for('message', timeout=60, check=lambda message: message.channel == ctx.channel and ctx.author == message.author)
st = st.content.replace('\n', '<br>')
a_file = open("welcomeMessageData.txt", "r")
list_of_lines = a_file.readlines()
list_of_lines[num + 2] = st + '\n'
a_file = open("welcomeMessageData.txt", "w")
a_file.writelines(list_of_lines)
a_file.close()
embed = discord.Embed(title='Success!', description=f'Title has been changed to {st}!')
await ctx.send(embed = embed)
if(setText.content.lower() == 'description' or setText.content.lower() == 'd'):
await ctx.send("Please enter the description for welcome message! (type: `None` for none)")
st1 = await bot.wait_for('message', timeout=60, check=lambda message: message.channel == ctx.channel and ctx.author == message.author)
st1 = st1.content.replace('\n', '<br>')
a_file = open("welcomeMessageData.txt", "r")
list_of_lines = a_file.readlines()
list_of_lines[num + 3] = st1 + '\n'
a_file = open("welcomeMessageData.txt", "w")
a_file.writelines(list_of_lines)
a_file.close()
embed = discord.Embed(title='Success!', description=f'Description has been changed to {st1}!')
await ctx.send(embed = embed)
if(setText.content.lower() == 'color' or setText.content.lower() == 'e'):
await ctx.send("Please enter the color for welcome message! (Hex code) (type: `None` for default)\n **eg. #0000FF**\n Details for hex code can be found in this link:\n https://www.colorhexa.com/")
stc = await bot.wait_for('message', timeout=60, check=lambda message: message.channel == ctx.channel and ctx.author == message.author)
stc = stc.content.replace('\n', '<br>')
a_file = open("welcomeMessageData.txt", "r")
list_of_lines = a_file.readlines()
list_of_lines[num + 4] = stc + '\n'
a_file = open("welcomeMessageData.txt", "w")
a_file.writelines(list_of_lines)
a_file.close()
embed = discord.Embed(title='Success!', description=f'Embed color has been changed to {stc}!', color = 0x00FF00)
await ctx.send(embed = embed)
if(setText.content.lower() == 'thumbnail' or setText.content.lower() == 'f'):
await ctx.send("Please enter the link of thumbnail for embed welcome message! (type: `None` if none) \n **eg. https://image.shutterstock.com/image-vector/welcome-poster-spectrum-brush-strokes-260nw-1146069941.jpg**")
stc = await bot.wait_for('message', timeout=60, check=lambda message: message.channel == ctx.channel and ctx.author == message.author)
stc = stc.content.replace('\n', '<br>')
a_file = open("welcomeMessageData.txt", "r")
list_of_lines = a_file.readlines()
list_of_lines[num + 5] = stc + '\n'
a_file = open("welcomeMessageData.txt", "w")
a_file.writelines(list_of_lines)
a_file.close()
embed = discord.Embed(title='Success!', description=f'Thumbnail has been changed to {stc}!')
await ctx.send(embed = embed)
if(setText.content.lower() == 'image' or setText.content.lower() == 'g'):
await ctx.send("Please enter the link of image for embed welcome message! (type: `None` for none) \n **eg. https://image.shutterstock.com/image-vector/welcome-poster-spectrum-brush-strokes-260nw-1146069941.jpg**")
stc = await bot.wait_for('message', timeout=60, check=lambda message: message.channel == ctx.channel and ctx.author == message.author)
stc = stc.content.replace('\n', '<br>')
a_file = open("welcomeMessageData.txt", "r")
list_of_lines = a_file.readlines()
list_of_lines[num + 6] = stc + '\n'
a_file = open("welcomeMessageData.txt", "w")
a_file.writelines(list_of_lines)
a_file.close()
embed = discord.Embed(title='Success!', description=f'Image has been changed to {stc}!')
await ctx.send(embed = embed)
else:
await ctx.send("**You havent set welcome message in your server!**\n Please type 'm!settings' and select welcome message.")
@help.command()
async def kick(ctx):
embed = discord.Embed(title="Kick", description="Kick a user from server.\n use: m!kick <@user>", color=0x0000FF)
embed.add_field(name='Example:', value='m!kick @jack')
await ctx.send(embed = embed)
@help.command()
async def ping(ctx):
embed = discord.Embed(title="Ping", description="Check for the bot latency.", color=0x0000FF)
await ctx.send(embed = embed)
@help.command()
async def ban(ctx):
embed = discord.Embed(title="Ban", description="Ban a user from server.\nuse: m!ban <@user> <reason>", color=0x0000FF)
embed.add_field(name='Example:', value='m!ban @jack sending inappropriate images')
await ctx.send(embed = embed)
@help.command()
async def unban(ctx):
embed = discord.Embed(title="Unban", description="Unban a user from server.\nuse: m!unban <@user>", color=0x0000FF)
await ctx.send(embed = embed)
@help.command()
async def mute(ctx):
embed = discord.Embed(title="Mute", description="Mute a user from server.\nuse: m!mute <@user>", color=0x0000FF)
embed.add_field(name='Example:', value='m!mute @jack')
await ctx.send(embed = embed)
@help.command(aliases=['setting'])
async def settings(ctx):
embed = discord.Embed(title="Settings [other names: setting]", description="Set anything to the bot. Follow the steps given.", color=0x0000FF)
await ctx.send(embed = embed)
@help.command()
async def farm(ctx):
embed = discord.Embed(title="Farm", description="Shows all of the farming price of this server.", color=0x0000FF)
await ctx.send(embed = embed)
@help.command()
async def info(ctx):
embed = discord.Embed(title="Info", description="Shows some important information of a server.", color=0x0000FF)
await ctx.send(embed = embed)
@help.command(name="math")
async def _math(ctx):
embed = discord.Embed(title="Math (Beta)", description="Solve your math problem as a calculator.", color=0x0000FF)
embed.add_field(name='Example:', value='m!math 15 * 9 - 88')
await ctx.send(embed = embed)
@help.command(aliases=['watch', 'yt'])
async def youtube(ctx):
embed = discord.Embed(title="Youtube other names: [watch, yt]", description="Search something on youtube and get nearest result.", color=0x0000FF)
embed.add_field(name='Example:', value='m!search how to make discord bot')
await ctx.send(embed = embed)
@help.command()
async def google(ctx):
embed = discord.Embed(title="Google", description="Search something on google and get nearest result (by link).\n Use: m!google <query>", color=0x0000FF)
embed.add_field(name='Example:', value='m!google how to make discord bot')
await ctx.send(embed = embed)
@help.command(aliases=['wikipedia'])
async def wiki(ctx):
embed = discord.Embed(title="Wikipedia [Other names: wiki]", description="Search something on wikipedia and get nearest result.\n Use: m!wiki <language code> <query>", color=0x0000FF)
embed.add_field(name='Example:', value="m!wiki en Avengers\n **Will give result in English.**\n Note: If you don't fill the language section, it will automatically return language in english.")
await ctx.send(embed = embed)
@help.command()
async def neko(ctx):
embed = discord.Embed(title="Neko", description="Send a random neko (anime cat).", color=0x0000FF)
await ctx.send(embed = embed)
@help.command()
async def purge(ctx):
embed = discord.Embed(title="Purge", description="Delete few messages on a channel.\n use: m!purge <message count>", color=0x0000FF)
embed.add_field(name='Example:', value="m!purge 10\n Delete 10 messages in the channel. ")
await ctx.send(embed = embed)
@help.command()
async def unmute(ctx):
embed = discord.Embed(title="Unmute", description="Unmute a user.\n use: m!unmute <@user_id>", color=0x0000FF)
embed.add_field(name='Example:', value="m!unmute `<@691231217936236560>`'")
await ctx.send(embed = embed)
@help.command(aliases=['rnumber', 'rnum'])
async def randomnumber(ctx):
embed = discord.Embed(title="Randomnumber [Other names: rnumber, rnum]", description="Return a random number between minimum and maximum.\n use: m!rnumber <Min> <Max>", color=0x0000FF)
embed.add_field(name='Example:', value="m!rnum 15, 100 \n **Will return a random number between 15 and 100.**")
await ctx.send(embed = embed)
@help.command(aliases=['av'])
async def avatar(ctx):
embed = discord.Embed(title="Avatar [Other names: av]", description="See selected user's avatar.\n use: m!avatar <@user>", color=0x0000FF)
embed.add_field(name='Example:', value="m!av @jack")
await ctx.send(embed = embed)
@help.command()
async def choose(ctx):
embed = discord.Embed(title="Choose", description="Choose a random things (Seperated by coma(',')).\n use: m!choose <value1>, <value2>, ...", color=0x0000FF)
embed.add_field(name='Example:', value="m!choose take a bath, eat dinner, brush teeth\n **Will give random answer: eg. eat dinner**")
await ctx.send(embed = embed)
@help.command(aliases=['tr', 'trans'])
async def translate(ctx):
embed = discord.Embed(title="Translate [Other names: tr, trans]", description="Translate a texts, sentences, words, etc.\n use: m!translate <language> <text>", color=0x0000FF)
embed.add_field(name='Example:', value="m!translate id hello, my name is miku.\n **Will give translated text in Bahasa Indonesia.**\n Note: If you don't fill the language section, it will automatically return language in english.")
await ctx.send(embed = embed)
@help.command()
async def version(ctx):
embed = discord.Embed(title="Version", description="See current version and all versions in the past.", color=0x0000FF)
await ctx.send(embed = embed)
@help.command(aliases=['createdat', 'created'])
async def createdate(ctx):
embed = discord.Embed(title="Translate [Other names: createdat, created]", description="See the crated date of a user.\n use: m!createdate <@user>", color=0x0000FF)
embed.add_field(name='Example:', value="m!createdate @jack")
await ctx.send(embed = embed)
@help.command(aliases=['t'])
async def talk(ctx):
embed = discord.Embed(title="talk [other names: t]", description='Talk with the bot\n use: m!talk <input>')
embed.addfield(name='Example:', value="m!talk hi, how are you \n **Bot will give an answer eg. I'm doing great, thanks for asking!** Note: If some answer does not make sense, use m!train to train the bot.\n ")
@help.command(name='train')
async def _train(ctx):
embed = discord.Embed(title="Train", description="Train bot's ai, so it's more efficiently return an answer.\n **After you do m!train, just follow the steps.", color=0x0000FF)
await ctx.send(embed = embed)
@help.command(name="kbbi")
async def _kbbi(ctx):
embed = discord.Embed(title="Kbbi", description="Search for Indonesian word in KBBI.\n use: m!kbbi <word>", color=0x0000FF)
embed.add_field(name="Example:", value="m!kbbi anime.")
@help.command(aliases=['len'])
async def length(ctx):
embed = discord.Embed(title="Length [Other names: len]", description="Find the length of a word, sentences, text, etc. \n use: m!length <text/word>", color=0x0000FF)
embed.add_field(name="Example:", value="m!length ⃟⃝⃟⃝⃟⃝⃟⃝⃟⃝⃟⃝⃟⃝⃟⃝⃟⃝.")
@bot.event
async def on_guild_join(guild):
joinedServer = guild.id
@bot.event
async def on_ready():
await bot.change_presence(activity=discord.Game(name="m!help"))
print('ok')
@bot.event
async def on_member_join(member):
gi = member.guild.id
with open("welcomeMessageData.txt", mode="r+") as file:
lines = [line.rstrip() for line in file.readlines()]
if(str(gi) in lines):
with open("welcomeMessageData.txt") as myFile:
for num, line in enumerate(myFile, 1):
if str(gi) in line:
break
nwi = lines.index(str(gi))
nw = lines[nwi + 1] #channel
nt = lines[nwi + 2] #normal text
wt = lines[nwi + 3] #embed title
wd = lines[nwi + 4] #embed description
wc = lines[nwi + 5] #embed color
wh = lines[nwi + 6] #embed thumbnail
wi = lines[nwi + 7] #embed image
nwint = int(nw)
channel = bot.get_channel(nwint)
sixteenIntegerHex = int(wc.replace("#", ""), 16)
readableHex = int(sixteenIntegerHex)
if(nt == 'None' or nt == None):
nt = None
else:
nt = nt.replace('<br>', '\n')
nt = nt.replace('{@user}', member.mention)
nt = nt.replace('{user}', member.name)
nt = nt.replace('{user_id}', str(member.id))
nt = nt.replace('{member_count}', len (member.guild.members))
if(wd == 'None' or wd == None):
wd == None
else:
wd = wd.replace('<br>', '\n')
wd = wd.replace('{@user}', member.mention)
wd = wd.replace('{user}', member.name)
wd = wd.replace('{user_id}', str(member.id))
wd = wd.replace('{member_count}', len (member.guild.members))
if(wt == 'None' or wt == None):
wt = None
else:
wt = wt.replace('<br>', '\n')
wt = wt.replace('{@user}', member.mention)
wt = wt.replace('{user}', member.name)
wt = wt.replace('{user_id}', str(member.id))
wt = wt.replace('{member_count}', len (member.guild.members))
if(wc == 'None'):
wc = 0x0000FF
else:
wc = wc.replace('<br>', '\n')
if(wh == 'None'):
wh = None
else:
wh = wh.replace('<br>', '\n')
if(wi == 'None'):
wi == None
else:
wi = wi.replace('<br>', '\n')
embed = discord.Embed(title=wt, description=wd, color=readableHex)
if(wi == None or wi == 'None'):
pass
else:
embed.set_image(url=wi)
if(wh == None or wh == "None"):
pass
else:
embed.set_thumbnail(url=wh)
if(nt == None or nt == "None"):
pass
else:
await channel.send(nt)
await channel.send(embed=embed)
@bot.listen()
async def on_message(message):
if message.author == bot.user:
return
if(not message.author.bot):
messageFilter = re.sub(r'[^\w]', ' ', message.content)
if(profanity.contains_profanity(messageFilter)):
await message.delete()
await message.channel.send(f"Hey, {message.author} do not send bad word!")
if(message.content == 'Æ'):
ae = ['Awas bikin streak Æ lagi...', 'Ikutan dong :D\nÆ', 'Dih Æ Æ Æ tross']
await message.channel.send(f'{random.choice(ae)}')
keep_alive()
bot.run(os.getenv("TOKEN"))
#added new attributes to welcome message editor:
#added new symbols on command math: ^ (Exponentiation)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment