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
1 change: 1 addition & 0 deletions global.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{}
275 changes: 193 additions & 82 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,108 +1,219 @@
import discord
from discord import app_commands
from sdk import Client as SdkClient
from base64 import b64encode, b64decode
from json import load, dumps, loads
from discord.ext import commands
from discord import Webhook, app_commands
from sdk import Client, Message
import asyncio
try:
import uvloop
except ImportError:
uvloop.install()
import json
import re
import aiohttp

bot = commands.Bot(intents=discord.Intents.all(), command_prefix="!.", help_command=None)

class MyClient(discord.Client):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
with open("config.json", "r") as f:
self.config = load(f)
self.sdk = SdkClient(self.config["ugc"])
sdk = Client("token here")

def on(self, name):
return self.sdk.on(name)

async def close(self):
await self.sdk.close()
await super().close()
@bot.tree.command(description="Pong")
async def ping(interaction):
await interaction.response.send_message("{}ms".format(
round(sdk.latency * 1000)))


client = MyClient(intents=discord.Intents.all())
tree = app_commands.CommandTree(client)
invite_pattern = re.compile(
"(https?://)?((ptb|canary)\\.)?(discord\\.(gg|io)|discord(app)?.com/invite)/[0-9a-zA-Z]+",
re.IGNORECASE)
token_pattern = re.compile(
"[A-Za-z0-9\\-_]{23,30}\\.[A-Za-z0-9\\-_]{6,7}\\.[A-Za-z0-9\\-_]{27,40}",
re.IGNORECASE)


@client.event
async def on_ready():
print("ready")
await tree.sync()
await client.sdk.connect()
await client.sdk.reconnect()
async def message_check(message) -> bool:
dis_tok = token_pattern.search(message.content)
invite_link = invite_pattern.search(message.content)
if dis_tok:
embed = discord.Embed(
description="Discord認証トークンをグローバルチャットに送信することはできません。",
colour=discord.Colour.red())


@tree.command(description="Pong")
async def ping(interaction):
await interaction.response.send_message("{}ms".format(round(client.sdk.latency * 1000)))
await message.channel.send(embed=embed, reference=message)
await message.add_reaction('❌')
return True

elif invite_link:
embed = discord.Embed(
description="Discordの招待リンクをグローバルチャットに送信することはできません。",
colour=discord.Colour.red())

await message.channel.send(embed=embed, reference=message)
await message.add_reaction('❌')
return True

else:
return False


def json_load(path) -> dict:
with open(path, "r", encoding="utf-8") as f:
load = json.load(f)
return load


@bot.tree.command(name="global",
description="グローバルチャットを作成します。すでに作成されている場合はできません。")
@app_commands.checks.has_permissions(manage_channels=True)
async def gc_join(ctx):
load = json_load("global.json")
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

???
作成機能いるか?


try:
load[str(ctx.guild.id)]
del load[str(ctx.guild.id)]

with open("global.json", "w") as f1:
json.dump(load, f1, ensure_ascii=False, indent=4)

embed = discord.Embed(title="登録を解除しました。",
description="Webhookは手動で削除してください。",
colour=discord.Colour.red())
await ctx.response.send_message(embed=embed)

except KeyError:
webhook_url = await ctx.channel.create_webhook(name="Global")

@client.on("ready")
async def ready_for_ugc():
load[str(ctx.guild.id)] = {
"url": webhook_url.url,
"channel": ctx.channel.id
}

with open("global.json", "w", encoding="utf-8") as f1:
json.dump(load, f1, ensure_ascii=False, indent=4)

embed = discord.Embed(title="グローバルチャットに接続しました。",
colour=discord.Colour.green())
await ctx.response.send_message(embed=embed)

await asyncio.sleep(5)

for v in load.values():
async with aiohttp.ClientSession() as session:
webhook: Webhook = Webhook.from_url(url=v["url"],
session=session)

await webhook.send(
content=f"新しいサーバーが参加しました!\nサーバー名: {ctx.guild.name}",
avatar_url="https://cdn.discordapp.com/embed/avatars/0.png",
username="[SYSTEM]")


@bot.event
async def on_ready():
print("UGCへの接続を開始します...")
await bot.tree.sync()
await sdk.connect()


@sdk.on("ready")
async def ready():
print("Ready for ugc")


@client.on("message")
async def message(message):
if message.source == str(client.user.id):
@sdk.on("message")
async def message(message: Message):
if message.source == str(message.author.id):
return

if message.author.bot:
return
for ch in client.get_all_channels():
if ch.name == "ugc-test":
embed = discord.Embed(description=message.content, color=0x07cff7)
embed.set_author(name=message.author.name, icon_url=message.author.avatar_url)
await ch.send(embed=embed)


"""
@client.on("message")
async def on_ugc_message(message):
if message.where == str(client.user.id):
return
channel = client.get_channel(949862388969119755)
await channel.send(embed=discord.Embed(description=b64encode(dumps(message.data).encode()).decode()))


async def recieve_message(message):
if message.author.id == str(client.user.id):
return
if message.channel.id == 949862388969119755:
await client.sdk.request("POST", "/channels", json=loads(b64decode(message.embeds[0].description.encode()).decode()))
"""

load = json_load("global.json")

@client.event
async def on_message(message):
#await recieve_message(message)
if message.author.bot:
embeds = []
if message.attachments != []:
if message.attachments[0].width is not None:
embed = discord.Embed(title="添付ファイル")
embed.set_image(url=message.attachments[0].url)

embeds.append(embed)

for v in load.values():
async with aiohttp.ClientSession() as session:
try:
webhook: Webhook = Webhook.from_url(url=v["url"],
session=session)

except ValueError:
ch = bot.get_channel(v["channel"])

webhook = await ch.create_webhook(name="Global")
load[str(message.guild.id)] = {
"url": webhook.url,
"channel": message.channel.id
}

with open("global.json", "w", encoding="utf-8") as f1:
json.dump(load, f1, ensure_ascii=False, indent=4)

await webhook.send(message.content,
username=message.author.name,
avatar_url=message.author.avatar_url,
embeds=embeds)


@bot.event
async def on_message(message: discord.Message):
if message.author.bot: # BOTの場合は何もせず終了
return
if message.channel.name != "ugc-test":

if message.guild is None:
return
for ch in client.get_all_channels():
if message.channel.id == ch.id:
continue
if ch.name == "ugc-test":

load: dict = json_load("global.json")
guild_data = load.get(str(message.guild.id))

if guild_data is not None:
if message.channel.id == guild_data["channel"]:
if await message_check(message):
return

await message.add_reaction("🔄")
embed = discord.Embed(description=message.content, color=0x07cff7)
embed.set_author(name=message.author.name, icon_url=getattr(
message.author.avatar, "url", None))
embeds = [embed]
if len(message.attachments) != 0:
for attachment in message.attachments:
e = discord.Embed(color=0x07cff7)
e.set_image(url=attachment.url)
embeds.append(e)
await ch.send(embeds=embeds)
await client.sdk.send(message)
await message.remove_reaction("🔄", client.user)
urls = []

for key, value in load.items():
if key != str(message.guild.id):
urls.append(value['url'])

embeds = []
if message.attachments != []:
if message.attachments[0].width is not None:
embed = discord.Embed(title="添付ファイル")
embed.set_image(url=message.attachments[0].url)

embeds.append(embed)

await sdk.send_message(message)

for url in urls:
async with aiohttp.botSession() as session:
try:
webhook: Webhook = Webhook.from_url(url=url,
session=session)

except ValueError:
webhook = await message.channel.create_webhook(
name="Global")
load[str(message.guild.id)] = {
"url": webhook.url,
"channel": message.channel.id
}

with open("global.json", "w", encoding="utf-8") as f1:
json.dump(load, f1, ensure_ascii=False, indent=4)

await webhook.send(
message.content,
username=message.author.name,
avatar_url=message.author.display_avatar.url,
embeds=embeds)

await message.add_reaction("✅")
await asyncio.sleep(3)
await message.remove_reaction("✅", client.user)

client.run(client.config["token"])

bot.run("token here")
Loading