Skip to content

Instantly share code, notes, and snippets.

@devxpy
Last active September 7, 2024 17:20
Show Gist options
  • Save devxpy/2abbe49fa2acb6958eb4d828f50c4467 to your computer and use it in GitHub Desktop.
Save devxpy/2abbe49fa2acb6958eb4d828f50c4467 to your computer and use it in GitHub Desktop.
FROM python
RUN pip install --no-cache-dir furl requests loguru
RUN curl -so main.py 'https://gist.githubusercontent.com/devxpy/2abbe49fa2acb6958eb4d828f50c4467/raw/db60e263a7e345bae31869f5e037f1f87bc54b6b/main.py'
CMD ["python", "main.py"]
import os
from time import sleep
import requests
from furl import furl
from loguru import logger
BOT_TOKEN = os.environ["BOT_TOKEN"]
GUILD_ID = os.environ["GUILD_ID"]
CLIENT_ID = os.environ["CLIENT_ID"]
BASE_URL = "https://discord.com/api/v10"
AUTH_HEADER = {
"Authorization": f"Bot {BOT_TOKEN}",
"User-Agent": f"DiscordBot (https://discord.com/oauth2/authorize?client_id={CLIENT_ID}, v0.1)",
}
def main():
while True:
channels = get_guild_channels(GUILD_ID)
channels.sort(key=channel_sort_order)
modify_guild_channel_positions(
GUILD_ID,
[dict(id=c["id"], position=i) for i, c in enumerate(channels)],
)
logger.info("new order: " + " | ".join([c["name"] for c in channels]))
sleep(10)
def channel_sort_order(channel: dict):
if channel.get("parent_id") and (last_message_id := channel.get("last_message_id")):
return -int(last_message_id) >> 22
if channel["type"] == 4 and (position := channel.get("position")):
return position
return 0
def get_guild_channels(guild_id: str) -> list:
r = requests.get(
furl(BASE_URL) / "guilds" / guild_id / "channels",
headers=AUTH_HEADER,
)
assert r.ok, r.text
ret = r.json()
logger.debug(ret)
return ret
def modify_guild_channel_positions(guild_id: str, data: list):
r = requests.patch(
furl(BASE_URL) / "guilds" / guild_id / "channels",
headers=AUTH_HEADER,
json=data,
)
assert r.ok, r.text
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment