Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 34 additions & 34 deletions bot/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import requests
from github import Github, Auth
from discord.ext import commands
from dotenv import load_dotenv
from dotenv import load_dotenv
import difflib
import asyncio
import time
Expand All @@ -25,7 +25,7 @@

user = github.get_user()
repo = user.get_repo("dm_open_ref")

intents=discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="?o", intents = intents)
Expand All @@ -42,7 +42,7 @@ def check_rate_limit():
'Accept': 'application/vnd.github.v3+json'
}
response = requests.get('https://api.github.com/rate_limit', headers=headers)

if response.status_code == 200:
rate_limit_info = response.json()
remaining = rate_limit_info['rate']['remaining']
Expand Down Expand Up @@ -72,7 +72,7 @@ async def send_commit_message(commit):
commit_message = commit['commit']['message']
author = commit['commit']['author']['name']
commit_url = commit['html_url']

embed = discord.Embed(
title="Update to Open Ref!",
url=commit_url,
Expand Down Expand Up @@ -115,8 +115,8 @@ async def periodic_commit_check():
while not bot.is_closed():
await check_for_new_commits()
await asyncio.sleep(3600)


'''
Bot queries stuff
'''
Expand Down Expand Up @@ -151,35 +151,35 @@ def ping_via_http(url) -> str:

@bot.event
async def on_ready():

custom_activity = discord.Activity(
type=discord.ActivityType.custom,
type=discord.ActivityType.custom,
state="Lummox has me locked up!"
)

await bot.change_presence(status=discord.Status.online, activity=custom_activity)
print(f"\n{bot.user} is online")
await bot.sync_commands()

class MyView(discord.ui.View):
def __init__(self, ref_text = "", timeout_time=120):
super().__init__(timeout = timeout_time)
self.ref_text = ref_text

@discord.ui.button(label="Click to View", style=discord.ButtonStyle.primary)
async def button_callback(self, button: discord.ui.Button, interaction: discord.Interaction):
await interaction.response.send_message(self.ref_text, ephemeral=True, embed=None)

def clean_query(filename, replace_with=""):
# Define illegal characters based on the operating system
illegal_chars = '\\/*?:"<>|'

# Build the cleaned filename by replacing illegal characters
cleaned = ''.join(char if char not in illegal_chars else replace_with for char in filename)

return cleaned

def special_characters(text) -> str:
def special_characters(text) -> str:
'''
Strips illegal characters from file names
Also performs minor cleanup of the file name
Expand Down Expand Up @@ -214,7 +214,7 @@ async def ncourage(ctx, *, user_input = None, user: discord.User = None):
username = user_input or ctx.author.name
messages = [f"You can do it, {username}", f"Go gettem, {username}", f"I believe in you, {username}"]
await ctx.send(random.choice(messages))

@bot.command(
brief="Spread the word of the best of the pokemon",
help="Sends a random Magikarp gif"
Expand All @@ -227,23 +227,23 @@ async def karp(ctx):
async def brr(ctx, *, wat_brr):
print(wat_brr)
await ctx.send(f"{wat_brr} go brr")

@bot.command(
brief="Blessings!",
help="Blessings bestowed upon thee!"
)
async def bless(ctx):
print("bless")
await ctx.send(f"https://media1.tenor.com/m/8Xlj8cg9L5EAAAAd/god-bless.gif")

@bot.command(
brief="hugs!",
help="send a hug gif"
)
async def hug(ctx):
print("hug")
await ctx.send(f"https://tenor.com/bf6qM.gif")

@bot.command(
brief="Punish Oref!",
help="o-ref has been naughty! Let the bot know by punishing it!"
Expand All @@ -252,7 +252,7 @@ async def bad(ctx):
print("bad bot")
messages = ["I've been a naughty bot", f"Please don't spank me again!", "So sorry. I'll do better.", "I'm just glad that you noticed me", "If you don't like it, fix it!"]
await ctx.send(random.choices(messages)[0])

@bot.command(
brief="greetings!",
help="salutations!"
Expand All @@ -269,7 +269,7 @@ async def good(ctx):
print("good bot")
messages = ["Thank you!", f"I exist to please", "You're welcome", "I'm just glad that you noticed me", "I'm glad you like me", "Why are you talking to me?"]
await ctx.send(random.choices(messages)[0])

@bot.command(
brief="Sends Praise!",
help="(Usually) sends praise towards whomever you tag, or yourself if you don't specify."
Expand All @@ -286,15 +286,15 @@ async def praise(ctx, *, user_input = None, user: discord.User = None):
brief="Displays a reference file",
help="""Searches reference files on open-ref using your input.
It will first search file names and paths, and if no matches are found, it will search file contents.
It displays the best match to your search."""
It displays the best match to your search."""
)
async def ref(ctx, *, query="DM"):
print(f"{ctx.guild}: {query}")

SEARCH_URL = "https://api.github.com/search/code"

headers = {'Authorization': f'Token {GIT_TOKEN}'}

if query in OVERRIDE_QUERIES:
match = OVERRIDE_QUERIES[query]
# await ctx.send(f"Override Query: {query} : {match}")
Expand Down Expand Up @@ -338,17 +338,17 @@ async def search(ctx, query, url, header, params):
unsorted_items = []
for item in search_results['items']:
unsorted_items.append(item['path'])

print(f"Pre-Sort:\n{[unsorted_items]}")

if len(unsorted_items) > 0:
match = unsorted_items[0]

sorted_items = difflib.get_close_matches(query, [item for item in unsorted_items], n = len(unsorted_items), cutoff=0.33)

if len(sorted_items) > 0:
match = sorted_items[0]

print(f"Sorted:\n{[sorted_items]}")

page = get_page(match)
Expand All @@ -371,12 +371,12 @@ async def ref_info(ctx, content):
timeout = 300
ref_view = MyView(ref_content, timeout)
bot_message = await ctx.send(embed=prettify(ref_content, ref_title, ref_link), view=ref_view)

await asyncio.sleep(timeout)
await bot_message.edit(view=None)

def prettify(content, page_title, link):

content = content[0:4000] + ("..." if len(content) > 4000 else "")
page_title = page_title.replace("#","")
page_title = page_title.replace("\\","")
Expand All @@ -388,10 +388,10 @@ def prettify(content, page_title, link):
)
#embed.add_field(name="", value = link, inline = False)
embed.set_footer(text="BYOND Version 516.1645")

return embed
# use: send(embed = prettify(content))

def get_page(item):
markdown_response = requests.get(f"{RAW}/{item}")
markdown_content = markdown_response.text
Expand Down Expand Up @@ -420,7 +420,7 @@ def fix_links(text) -> str:
path = text[start_index + len(start_marker):end_index]
new_link = f"]"
result.append(new_link)

i = end_index + 1
return ''.join(result)

Expand All @@ -430,9 +430,9 @@ def cleanup_output(text):
text = text.replace("> [!TIP]", "")
text = text.replace("+ ", "- ")
text = fix_links(text)

text = text[0:text.find("> **See also:**")]

return text

bot.loop.create_task(periodic_commit_check())
Expand Down
Loading