Skip to content

Commit

Permalink
Merge pull request Seniru#34 from We-Talk-a-Lot/master
Browse files Browse the repository at this point in the history
Give coomits
  • Loading branch information
Seniru authored Jul 31, 2021
2 parents dbd3cde + 6ba9519 commit dbcd6a3
Show file tree
Hide file tree
Showing 12 changed files with 389 additions and 24 deletions.
139 changes: 138 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,141 @@ discordia.log
gateway.json
init.sh
.env
*.pyc

__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/
3 changes: 3 additions & 0 deletions .gitmodules
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[submodule "discordslashcommands"]
path = discordslashcommands
url = https://github.com/mactul/discordslashcommands
1 change: 1 addition & 0 deletions discordslashcommands
Submodule discordslashcommands added at 0b2454
4 changes: 2 additions & 2 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
aiohttp==3.7.4.post0
aiotfm==1.4.0rc0
aiotfm>=1.4.2
async-timeout==3.0.1
discord-py-slash-command==1.1.2
discord-components==1.1.4
discord.py==1.7.1
multidict==5.1.0
w3lib==1.22.0
Expand Down
5 changes: 5 additions & 0 deletions script.bash
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
cd discordslashcommands
pip install -r requirements.txt
python setup.py install
cd ..

function run() {
python src/main.py || run
}
Expand Down
100 changes: 95 additions & 5 deletions src/bots/Discord.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
import asyncio
import json
import os
import random
import re
from datetime import datetime, timedelta

import discord
import os
import utils
import json
import discordslashcommands as slash
import requests

import utils
from data import data
from discord_components import Button, DiscordComponents, Select, SelectOption

from bots.cmd_handler import commands

WANDBOX_ENDPOINT = "https://wandbox.org/api"
Expand All @@ -26,6 +32,7 @@ def __init__(self):

async def on_ready(self):
print("[INFO][DISCORD] Client is ready!")
await asyncio.sleep(3)
self.main_guild = self.get_guild(data["guild"])
self.data_channel = self.get_guild(data["data_guild"]).get_channel(data["channels"]["data"])

Expand All @@ -38,9 +45,19 @@ async def on_ready(self):
self.mod_data = await self.data_channel.fetch_message(data["data"]["mod"])
self.mod_data = json.loads(self.mod_data.content[7:-3])

self.slash = {}#slash.Manager(self)
DiscordComponents(self)

await self.start_period_tasks()

async def on_message(self, message):

# temporary code
if (str(message.channel.id) == os.getenv("GRAVEYARD")) and (self.main_guild.get_role(data["roles"]["mafia_dead"]) in message.author.roles):
await self.get_channel(int(os.getenv("MEDIUM_CHAT"))).send(":speaking_head: **[**<@{}>**]** `{}`".format(message.author.id, message.content))

if message.content.startswith(">"):
content = re.match(r"^>\s*(.+)", message.content).group(1)
content = re.match(r"^>\s*((.|\n)*)", message.content).group(1)
args = re.split(r"\s+", content)

if args[0] in commands and commands[args[0]]["discord"]:
Expand Down Expand Up @@ -90,6 +107,47 @@ async def on_message(self, message):

await message.reply(embed = discord.Embed.from_dict(res))

elif self.user.id in message.raw_mentions:
fact = requests.get("https://uselessfacts.jsph.pl/random.md?language=en", headers = { "User-Agent": "Seniru" }).text
await message.reply(embed = discord.Embed.from_dict({
"title": "{}! Wanna hear a fact? :bulb:".format(random.choice([
"Hi", "Hello", "Howdy", "Hola", "Yo", "Wassup", "Hola", "Namasthe", "Hi there", "Greetings",
"What's going on", "How's everything", "Good to see you", "Great to see you", "Nice to see you",
"Saluton", "What's new", "How are you feeling today","Hey there"
])),
"description": fact,
"color": 0x2987ba
}))

async def on_interaction(self, member, interaction):
await interaction.end(content = "** **")
cmd_name = interaction.command.name
if cmd_name in commands and commands[cmd_name]["discord"]:
cmd = commands[cmd_name]
interaction.author = self.main_guild.get_member(interaction._member_data["user"]["id"])
interaction.member = interaction.author
if cmd["allowed_roles"]:
for role in cmd["allowed_roles"]:
if self.main_guild.get_role(role) in interaction.member.roles:
break
else:
return await interaction.channel.send(embed = discord.Embed.from_dict({
"title": ":x: Missing permissions",
"description": "You need 1 of the following roles to use this command: \n{}".format(
", ".join(list(map(lambda role: "<@&{}>".format(role), cmd["allowed_roles"])))
),
"color": 0xcc0000
}))
interaction.reply = self.main_guild.get_channel(interaction.channel.id).send
interaction.send = self.main_guild.get_channel(interaction.channel.id).send
interaction.options = list(map(lambda o: o.value, interaction.command.options))
interaction.mentions = list(
map(
lambda m: self.main_guild.get_member(int(re.match(r".*?(\d+).*", m)[1])),
filter(lambda o: re.match(r"^<@!?(\d+)>$", o), interaction.options)
))
await cmd["f"](interaction.options, interaction, self)

async def on_member_join(self, member):
error = False
try:
Expand Down Expand Up @@ -133,6 +191,11 @@ async def on_member_update(self, before, after):

await after.add_roles(rank_role)

async def on_error(self, evt, *args, **kwargs):
import sys
exe_type, val, traceback = sys.exc_info()
await self.get_channel(data["channels"]["tribe_chat"]).send(f"<@!522972601488900097> `[ERR][DISCORD@evt_{evt}]` ```py\n{exe_type.__name__}@{traceback.tb_frame.f_code.co_filename}-{traceback.tb_lineno}: {val}```")

async def send_verification_key(self, member):
key = utils.generate_random_key(member.id)
await member.send(f"Here's your verification key! `{key}\n`Whisper the following to Wtal#5272 (`/c Wtal#5272`) to get verified\n")
Expand Down Expand Up @@ -163,6 +226,33 @@ async def update_mod_data(self):
```
""".format(json.dumps(self.mod_data)))

async def start_period_tasks(self):
print("[INFO] Checking for periodic tasks...")
# check qotd
await commands["qotd"]["f"](["ask"], None, self)
# other daily tasks
last_daily_data = await self.data_channel.fetch_message(data["data"]["daily"])
now = datetime.now()
if now > datetime.fromtimestamp(float(last_daily_data.content)) + timedelta(days=1):
for task in (("bday", []), ("stats", [])):
try:
await commands[task[0]]["f"](task[1], None, self)
except Exception as e:
await self.main_guild.get_channel(data["data"]["channels"]["admin"]).send(
"<@!522972601488900097> [DAILY TASK FAILURE|{}] `{}`\n```\n{}```"
.format(task[0], e, e.with_traceback()))
await last_daily_data.edit(content=str(now.timestamp()))
await asyncio.sleep(1 * 60 * 5)
await self.start_period_tasks()

async def set_status(self):
tribe_total = await self.tfm.getTribe(True)
tribe_online = await self.tfm.getTribe(False)
await self.change_presence(
status=discord.Status.online,
activity=discord.Activity(type = discord.ActivityType.playing, name = "{} / {} online!".format(len(tribe_online.members), len(tribe_total.members)))
)

def search_member(self, name, deep_check=False):
if member := self.main_guild.get_member_named(utils.get_discord_nick_format(name)):
return member
Expand Down
Loading

0 comments on commit dbcd6a3

Please sign in to comment.