Skip to content

Commit

Permalink
Merge pull request #216 from bobloy/red_35
Browse files Browse the repository at this point in the history
Mostly async stuff
  • Loading branch information
bobloy committed Jun 19, 2023
2 parents 803175b + cf10576 commit 43a39cc
Show file tree
Hide file tree
Showing 49 changed files with 287 additions and 133 deletions.
8 changes: 5 additions & 3 deletions announcedaily/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
from .announcedaily import AnnounceDaily


def setup(bot: Red):
async def setup(bot: Red):
daily = AnnounceDaily(bot)
bot.add_cog(daily)
bot.loop.create_task(daily.check_day())
r = bot.add_cog(daily)
if r is not None:
await r
bot.loop.create_task(daily.check_day())
9 changes: 6 additions & 3 deletions audiotrivia/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,11 @@
async def setup(bot: Red):
if bot.get_cog("Trivia"):
print("Trivia is already loaded, attempting to unload it first")
bot.remove_cog("Trivia")
await bot.remove_cog("Trivia")
await bot.remove_loaded_package("trivia")
bot.unload_extension("trivia")
await bot.unload_extension("trivia")

bot.add_cog(AudioTrivia(bot))
cog = AudioTrivia(bot)
r = bot.add_cog(cog)
if r is not None:
await r
7 changes: 5 additions & 2 deletions ccrole/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
from .ccrole import CCRole


def setup(bot):
bot.add_cog(CCRole(bot))
async def setup(bot):
cog = CCRole(bot)
r = bot.add_cog(cog)
if r is not None:
await r
20 changes: 9 additions & 11 deletions ccrole/ccrole.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,12 @@
import re

import discord
from discord.ext.commands import RoleConverter, Greedy, CommandError, ArgumentParsingError
from discord.ext.commands import (
RoleConverter,
Greedy,
CommandError,
ArgumentParsingError,
)
from discord.ext.commands.view import StringView
from redbot.core import Config, checks, commands
from redbot.core.bot import Red
Expand Down Expand Up @@ -107,10 +112,7 @@ async def ccrole_add(self, ctx, command: str):
return

# Roles to add
await ctx.send(
"What roles should it add?\n"
"Say `None` to skip adding roles"
)
await ctx.send("What roles should it add?\n" "Say `None` to skip adding roles")

def check(m):
return m.author == author and m.channel == channel
Expand All @@ -129,10 +131,7 @@ def check(m):
return

# Roles to remove
await ctx.send(
"What roles should it remove?\n"
"Say `None` to skip removing roles"
)
await ctx.send("What roles should it remove?\n" "Say `None` to skip removing roles")
try:
answer = await self.bot.wait_for("message", timeout=120, check=check)
except asyncio.TimeoutError:
Expand All @@ -148,8 +147,7 @@ def check(m):

# Roles to use
await ctx.send(
"What roles are allowed to use this command?\n"
"Say `None` to allow all roles"
"What roles are allowed to use this command?\n" "Say `None` to allow all roles"
)

try:
Expand Down
4 changes: 3 additions & 1 deletion chatter/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
async def setup(bot):
cog = Chatter(bot)
await cog.initialize()
bot.add_cog(cog)
r = bot.add_cog(cog)
if r is not None:
await r


# __all__ = (
Expand Down
25 changes: 18 additions & 7 deletions chatter/chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,17 @@

import discord
from chatterbot import ChatBot
from chatterbot.comparisons import JaccardSimilarity, LevenshteinDistance, SpacySimilarity
from chatterbot.comparisons import (
JaccardSimilarity,
LevenshteinDistance,
SpacySimilarity,
)
from chatterbot.response_selection import get_random_response
from chatterbot.trainers import ChatterBotCorpusTrainer, ListTrainer, UbuntuCorpusTrainer
from chatterbot.trainers import (
ChatterBotCorpusTrainer,
ListTrainer,
UbuntuCorpusTrainer,
)
from redbot.core import Config, checks, commands
from redbot.core.commands import Cog
from redbot.core.data_manager import cog_data_path
Expand Down Expand Up @@ -66,7 +74,12 @@ def __init__(self, bot):
super().__init__()
self.bot = bot
self.config = Config.get_conf(self, identifier=6710497116116101114)
default_global = {"learning": True, "model_number": 0, "algo_number": 0, "threshold": 0.90}
default_global = {
"learning": True,
"model_number": 0,
"algo_number": 0,
"threshold": 0.90,
}
self.default_guild = {
"whitelist": None,
"days": 1,
Expand Down Expand Up @@ -115,7 +128,6 @@ async def initialize(self):
self.chatbot = self._create_chatbot()

def _create_chatbot(self):

return ChatBot(
"ChatterBot",
# storage_adapter="chatterbot.storage.SQLStorageAdapter",
Expand Down Expand Up @@ -155,7 +167,6 @@ def new_conversation(msg, sent, out_in, delta):
send_time = after - timedelta(days=100) # Makes the first message a new message

try:

async for message in channel.history(
limit=None, after=after, oldest_first=True
).filter(
Expand Down Expand Up @@ -195,7 +206,8 @@ def _train_twitter(self, *args, **kwargs):

def _train_ubuntu(self):
trainer = UbuntuCorpusTrainer(
self.chatbot, ubuntu_corpus_data_directory=cog_data_path(self) / "ubuntu_data"
self.chatbot,
ubuntu_corpus_data_directory=cog_data_path(self) / "ubuntu_data",
)
trainer.train()
return True
Expand Down Expand Up @@ -696,7 +708,6 @@ async def on_message_without_command(self, message: discord.Message):
text = message.clean_content

async with ctx.typing():

if is_reply:
in_response_to = message.reference.resolved.content
elif self._last_message_per_channel[ctx.channel.id] is not None:
Expand Down
7 changes: 5 additions & 2 deletions coglint/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
from .coglint import CogLint


def setup(bot):
bot.add_cog(CogLint(bot))
async def setup(bot):
cog = CogLint(bot)
r = bot.add_cog(cog)
if r is not None:
await r
10 changes: 7 additions & 3 deletions conquest/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,11 @@ async def setup(bot):
data_manager.bundled_data_path(cog)
await cog.load_data()

bot.add_cog(cog)
r = bot.add_cog(cog)
if r is not None:
await r

cog2 = MapMaker(bot)
bot.add_cog(cog2)
cog2 = MapMaker(bot)
r2 = bot.add_cog(cog2)
if r2 is not None:
await r2
3 changes: 2 additions & 1 deletion conquest/conquest.py
Original file line number Diff line number Diff line change
Expand Up @@ -328,7 +328,8 @@ async def _conquest_numbered(self, ctx: commands.Context):
)

current_numbered_img.save(
self.data_path / self.current_map / f"current_numbered.{self.ext}", self.ext_format
self.data_path / self.current_map / f"current_numbered.{self.ext}",
self.ext_format,
)

await self._send_maybe_zoomed_map(
Expand Down
10 changes: 7 additions & 3 deletions conquest/regioner.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,8 @@ def floodfill(image, xy, value, border=None, thresh=0) -> set:
while edge:
filled_pixels.update(edge)
new_edge = set()
for (x, y) in edge: # 4 adjacent method
for (s, t) in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)):
for x, y in edge: # 4 adjacent method
for s, t in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)):
# If already processed, or if a coordinate is negative, skip
if (s, t) in full_edge or s < 0 or t < 0:
continue
Expand All @@ -76,7 +76,11 @@ def floodfill(image, xy, value, border=None, thresh=0) -> set:

class Regioner:
def __init__(
self, filepath: pathlib.Path, filename: str, wall_color="black", region_color="white"
self,
filepath: pathlib.Path,
filename: str,
wall_color="black",
region_color="white",
):
self.filepath = filepath
self.filename = filename
Expand Down
7 changes: 5 additions & 2 deletions dad/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
from .dad import Dad


def setup(bot):
bot.add_cog(Dad(bot))
async def setup(bot):
cog = Dad(bot)
r = bot.add_cog(cog)
if r is not None:
await r
7 changes: 5 additions & 2 deletions exclusiverole/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
from .exclusiverole import ExclusiveRole


def setup(bot):
bot.add_cog(ExclusiveRole(bot))
async def setup(bot):
cog = ExclusiveRole(bot)
r = bot.add_cog(cog)
if r is not None:
await r
2 changes: 1 addition & 1 deletion fifo/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,5 @@ async def setup(bot):
await cog.initialize()


def teardown(bot):
async def teardown(bot):
pass
30 changes: 24 additions & 6 deletions fifo/fifo.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,11 @@
from redbot.core.commands import TimedeltaConverter
from redbot.core.utils.chat_formatting import humanize_timedelta, pagify

from .datetime_cron_converters import CronConverter, DatetimeConverter, TimezoneConverter
from .datetime_cron_converters import (
CronConverter,
DatetimeConverter,
TimezoneConverter,
)
from .task import Task

schedule_log = logging.getLogger("red.fox_v3.fifo.scheduler")
Expand Down Expand Up @@ -104,7 +108,6 @@ def cog_unload(self):
self.scheduler.shutdown()

async def initialize(self):

job_defaults = {
"coalesce": True, # Multiple missed triggers within the grace time will only fire once
"max_instances": 5, # This is probably way too high, should likely only be one
Expand All @@ -117,7 +120,9 @@ async def initialize(self):
# Default executor is already AsyncIOExecutor
self.scheduler = AsyncIOScheduler(job_defaults=job_defaults, logger=schedule_log)

from .redconfigjobstore import RedConfigJobStore # Wait to import to prevent cyclic import
from .redconfigjobstore import (
RedConfigJobStore,
) # Wait to import to prevent cyclic import

self.jobstore = RedConfigJobStore(self.config, self.bot)
await self.jobstore.load_from_config()
Expand Down Expand Up @@ -375,7 +380,9 @@ async def fifo_details(self, ctx: commands.Context, task_name: str):
embed = discord.Embed(title=f"Task: {task_name}")

embed.add_field(
name="Task command", value=f"{ctx.prefix}{task.get_command_str()}", inline=False
name="Task command",
value=f"{ctx.prefix}{task.get_command_str()}",
inline=False,
)

guild: discord.Guild = self.bot.get_guild(task.guild_id)
Expand Down Expand Up @@ -470,7 +477,14 @@ async def fifo_add(self, ctx: commands.Context, task_name: str, *, command_to_ex
)
return

task = Task(task_name, ctx.guild.id, self.config, ctx.author.id, ctx.channel.id, self.bot)
task = Task(
task_name,
ctx.guild.id,
self.config,
ctx.author.id,
ctx.channel.id,
self.bot,
)
await task.set_commmand_str(command_to_execute)
await task.save_all()
await ctx.tick()
Expand Down Expand Up @@ -553,7 +567,11 @@ async def fifo_trigger_interval(

@fifo_trigger.command(name="relative")
async def fifo_trigger_relative(
self, ctx: commands.Context, task_name: str, *, time_from_now: TimedeltaConverter
self,
ctx: commands.Context,
task_name: str,
*,
time_from_now: TimedeltaConverter,
):
"""
Add a "run once" trigger at a time relative from now to the specified task
Expand Down
25 changes: 19 additions & 6 deletions fifo/task.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ def parse_triggers(data: Union[Dict, None]):
"content",
"nonce",
"reference",
"_edited_timestamp" # New 7/23/21
"_edited_timestamp", # New 7/23/21
]

things_fakemessage_sets_by_default = {
Expand All @@ -119,11 +119,15 @@ def __init__(self, *args, message: discord.Message, **kwargs):
self.id = time_snowflake(datetime.utcnow(), high=False) # Pretend to be now
self.type = discord.MessageType.default

def _rebind_cached_references_backport(self, guild: discord.Guild, channel: discord.TextChannel) -> Callable:
def _rebind_cached_references_backport(
self, guild: discord.Guild, channel: discord.TextChannel
) -> Callable:
def check_sig(method_name, *params):
method = getattr(self, method_name, None)
return method and ismethod(method) and list(signature(method).parameters) == list(params)

return (
method and ismethod(method) and list(signature(method).parameters) == list(params)
)

if check_sig("_rebind_cached_references", "new_guild", "new_channel"):
self._rebind_cached_references(guild, channel)
elif check_sig("_rebind_channel_reference", "new_channel"):
Expand Down Expand Up @@ -199,7 +203,13 @@ class Task:
}

def __init__(
self, name: str, guild_id, config: Config, author_id=None, channel_id=None, bot: Red = None
self,
name: str,
guild_id,
config: Config,
author_id=None,
channel_id=None,
bot: Red = None,
):
self.name = name
self.guild_id = guild_id
Expand All @@ -220,7 +230,10 @@ async def _encode_time_triggers(self):
td: timedelta = t["time_data"]

triggers.append(
{"type": t["type"], "time_data": {"days": td.days, "seconds": td.seconds}}
{
"type": t["type"],
"time_data": {"days": td.days, "seconds": td.seconds},
}
)
continue

Expand Down
6 changes: 4 additions & 2 deletions flag/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from .flag import Flag


def setup(bot):
bot.add_cog(Flag(bot))
async def setup(bot):
r = bot.add_cog(Flag(bot))
if r is not None:
await r
Loading

0 comments on commit 43a39cc

Please sign in to comment.