Skip to content

Commit fa135eb

Browse files
committed
Improve and error handling for update and autoupdate features.
1 parent 77489be commit fa135eb

File tree

3 files changed

+136
-63
lines changed

3 files changed

+136
-63
lines changed

bot.py

Lines changed: 37 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717

1818
import discord
1919
import isodate
20-
from aiohttp import ClientSession
20+
from aiohttp import ClientSession, ClientResponseError
2121
from discord.ext import commands, tasks
2222
from discord.ext.commands.view import StringView
2323
from emoji import UNICODE_EMOJI
@@ -630,6 +630,8 @@ async def on_ready(self):
630630
)
631631
logger.warning("If the external servers are valid, you may ignore this message.")
632632

633+
self.post_metadata.start()
634+
self.autoupdate.start()
633635
self._started = True
634636

635637
async def convert_emoji(self, name: str) -> str:
@@ -1581,6 +1583,7 @@ async def before_post_metadata(self):
15811583
await self.wait_for_connected()
15821584
if not self.config.get("data_collection") or not self.guild:
15831585
self.post_metadata.cancel()
1586+
return
15841587

15851588
logger.debug("Starting metadata loop.")
15861589
logger.line("debug")
@@ -1591,44 +1594,50 @@ async def autoupdate(self):
15911594
latest = changelog.latest_version
15921595

15931596
if self.version < parse_version(latest.version):
1594-
if self.hosting_method == HostingMethod.HEROKU:
1597+
try:
1598+
# update fork if gh_token exists
15951599
data = await self.api.update_repository()
1600+
except InvalidConfigError:
1601+
data = {}
1602+
except ClientResponseError as exc:
1603+
logger.error(f"Autoupdate failed! Status {exc.status}.")
1604+
logger.error(f"Message: {exc.message}")
1605+
self.autoupdate.cancel()
1606+
return
1607+
if self.hosting_method == HostingMethod.HEROKU:
1608+
commit_data = data.get("data")
1609+
if not commit_data:
1610+
return
15961611

1597-
embed = discord.Embed(color=self.main_color)
1612+
logger.info("Bot has been updated.")
1613+
1614+
if not self.config["update_notifications"]:
1615+
return
15981616

1599-
commit_data = data["data"]
1617+
embed = discord.Embed(color=self.main_color)
1618+
message = commit_data["commit"]["message"]
1619+
html_url = commit_data["html_url"]
1620+
short_sha = commit_data["sha"][:6]
16001621
user = data["user"]
1622+
embed.add_field(
1623+
name="Merge Commit",
1624+
value=f"[`{short_sha}`]({html_url}) " f"{message} - {user['username']}",
1625+
)
16011626
embed.set_author(
16021627
name=user["username"] + " - Updating Bot",
16031628
icon_url=user["avatar_url"],
16041629
url=user["url"],
16051630
)
16061631

1607-
embed.set_footer(text=f"Updating Modmail v{self.version} " f"-> v{latest.version}")
1632+
embed.set_footer(text=f"Updating Modmail v{self.version} -> v{latest.version}")
16081633

16091634
embed.description = latest.description
16101635
for name, value in latest.fields.items():
16111636
embed.add_field(name=name, value=value)
16121637

1613-
if commit_data:
1614-
message = commit_data["commit"]["message"]
1615-
html_url = commit_data["html_url"]
1616-
short_sha = commit_data["sha"][:6]
1617-
embed.add_field(
1618-
name="Merge Commit",
1619-
value=f"[`{short_sha}`]({html_url}) " f"{message} - {user['username']}",
1620-
)
1621-
logger.info("Bot has been updated.")
1622-
channel = self.log_channel
1623-
if self.config["update_notifications"]:
1624-
await channel.send(embed=embed)
1638+
channel = self.update_channel
1639+
await channel.send(embed=embed)
16251640
else:
1626-
try:
1627-
# update fork if gh_token exists
1628-
await self.api.update_repository()
1629-
except InvalidConfigError:
1630-
pass
1631-
16321641
command = "git pull"
16331642
proc = await asyncio.create_subprocess_shell(
16341643
command,
@@ -1642,7 +1651,7 @@ async def autoupdate(self):
16421651

16431652
if err and not res:
16441653
logger.warning(f"Autoupdate failed: {err}")
1645-
self.autoupdate_loop.cancel()
1654+
self.autoupdate.cancel()
16461655
return
16471656

16481657
elif res != "Already up to date.":
@@ -1659,7 +1668,7 @@ async def autoupdate(self):
16591668
description="If you do not have an auto-restart setup, please manually start the bot.",
16601669
color=self.main_color,
16611670
)
1662-
embed.set_footer(text=f"Updating Modmail v{self.version} " f"-> v{latest.version}")
1671+
embed.set_footer(text=f"Updating Modmail v{self.version} -> v{latest.version}")
16631672
if self.config["update_notifications"]:
16641673
await channel.send(embed=embed)
16651674
return await self.close()
@@ -1671,16 +1680,16 @@ async def before_autoupdate(self):
16711680

16721681
if self.config.get("disable_autoupdates"):
16731682
logger.warning("Autoupdates disabled.")
1674-
self.autoupdate_loop.cancel()
1683+
self.autoupdate.cancel()
16751684

16761685
if self.hosting_method == HostingMethod.DOCKER:
16771686
logger.warning("Autoupdates disabled as using Docker.")
1678-
self.autoupdate_loop.cancel()
1687+
self.autoupdate.cancel()
16791688

16801689
if not self.config.get("github_token") and self.hosting_method == HostingMethod.HEROKU:
16811690
logger.warning("GitHub access token not found.")
16821691
logger.warning("Autoupdates disabled.")
1683-
self.autoupdate_loop.cancel()
1692+
self.autoupdate.cancel()
16841693

16851694
def format_channel_name(self, author, exclude_channel=None, force_null=False):
16861695
"""Sanitises a username for use with text channel names

cogs/utility.py

Lines changed: 25 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1931,15 +1931,15 @@ async def github(self, ctx):
19311931
async def update(self, ctx, *, flag: str = ""):
19321932
"""
19331933
Update Modmail.
1934-
To stay up-to-date with the latest commit rom GitHub, specify "force" as the flag.
1934+
To stay up-to-date with the latest commit from GitHub, specify "force" as the flag.
19351935
"""
19361936

19371937
changelog = await Changelog.from_url(self.bot)
19381938
latest = changelog.latest_version
19391939

19401940
desc = (
19411941
f"The latest version is [`{self.bot.version}`]"
1942-
"(https://github.com/kyb3r/modmail/blob/master/bot.py#L25)"
1942+
"(https://github.com/kyb3r/modmail/blob/master/bot.py#L1)"
19431943
)
19441944

19451945
if self.bot.version >= parse_version(latest.version) and flag.lower() != "force":
@@ -1951,16 +1951,35 @@ async def update(self, ctx, *, flag: str = ""):
19511951
embed.set_author(name=user["username"], icon_url=user["avatar_url"], url=user["url"])
19521952
await ctx.send(embed=embed)
19531953
else:
1954-
if self.bot.hosting_method == HostingMethod.HEROKU:
1954+
try:
1955+
# update fork if gh_token exists
19551956
data = await self.bot.api.update_repository()
1957+
except InvalidConfigError:
1958+
data = {}
1959+
except ClientResponseError as exc:
1960+
embed = discord.Embed(
1961+
title="Update failed",
1962+
description=f"Error status {exc.status}. {exc.message}",
1963+
color=self.bot.error_color,
1964+
)
1965+
return await ctx.send(embed=embed)
1966+
1967+
if self.bot.hosting_method == HostingMethod.HEROKU:
1968+
if not data:
1969+
# invalid gh_token
1970+
embed = discord.Embed(
1971+
title="Update failed",
1972+
description="Invalid Github token.",
1973+
color=self.bot.error_color,
1974+
)
1975+
return await ctx.send(embed=embed)
19561976

19571977
commit_data = data["data"]
19581978
user = data["user"]
1959-
19601979
if commit_data and commit_data.get("html_url"):
19611980
embed = discord.Embed(color=self.bot.main_color)
19621981

1963-
embed.set_footer(text=f"Updating Modmail v{self.bot.version} " f"-> v{latest.version}")
1982+
embed.set_footer(text=f"Updating Modmail v{self.bot.version} -> v{latest.version}")
19641983

19651984
embed.set_author(
19661985
name=user["username"] + " - Updating bot",
@@ -1978,21 +1997,14 @@ async def update(self, ctx, *, flag: str = ""):
19781997
else:
19791998
embed = discord.Embed(
19801999
title="Already up to date",
1981-
description="No further updates required",
2000+
description="No further updates required.",
19822001
color=self.bot.main_color,
19832002
)
19842003
embed.set_footer(text="Force update")
19852004
embed.set_author(name=user["username"], icon_url=user["avatar_url"], url=user["url"])
19862005
await ctx.send(embed=embed)
19872006
else:
1988-
# update fork if gh_token exists
1989-
try:
1990-
await self.bot.api.update_repository()
1991-
except InvalidConfigError:
1992-
pass
1993-
19942007
command = "git pull"
1995-
19962008
proc = await asyncio.create_subprocess_shell(
19972009
command,
19982010
stderr=PIPE,

0 commit comments

Comments
 (0)