Last active
February 13, 2019 16:40
-
-
Save EcmaXp/6c4519ebdbf24bea42594370dea7b3d5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from sys import version_info | |
import asyncio | |
try: | |
# noinspection PyPackageRequirements | |
import discord | |
except ImportError: | |
discord = False | |
PY3 = version_info > (3, 5) | |
AUTHOR = "PurePi" | |
VERSION = (0, 1, 1) | |
NAME = "Discord Relay" | |
SUMMARY = "Minecraft-to-Discord and Discord-to-Minecraft chat relay" | |
DESCRIPTION = """ This plugin sends all players' messages to a Discord server | |
and broadcasts messages from the Discord server to the Minecraft server | |
""" | |
DISABLED = False | |
# noinspection PyAttributeOutsideInit,PyPep8Naming | |
# noinspection PyUnusedLocal,PyUnresolvedReferences,PyCompatibility | |
class Main: | |
def __init__(self, api, log): | |
self.api = api | |
self.log = log | |
def onEnable(self): | |
if not discord or not PY3: | |
self.log.warning( | |
"Discord Relay plugin requires Python 3 and the discord import." | |
) | |
return False | |
from threading import Thread | |
Thread(target=lambda: self.func()).start() | |
def func(self): | |
loop = asyncio.new_event_loop() | |
asyncio.set_event_loop(loop) | |
self.client = client = discord.Client(loop=loop) | |
self.server = discord.Server(id="<SERVER-ID>") | |
self.sendChannel = discord.Channel( | |
name="<CHANNEL-NAME>", server=self.server, id="<CHANNEL-ID>" | |
) | |
self.api.registerEvent("player.message", self.player_message) | |
@client.event | |
async def on_message(message): | |
userName = message.author.nick or message.author.name | |
message = message.clean_content | |
if userName == "<BOT-NAME>: # ...? | |
# myself | |
return | |
text = f"[{userName}] {message}" | |
self.api.minecraft.broadcast(text) | |
@client.event | |
async def on_ready(): | |
await self.client.send_message(self.sendChannel, "Server started.") | |
loop.run_until_complete(self.client.start("<TOKEN>")) | |
def onDisable(self): | |
self.client.logout() | |
def player_message(self, payload): | |
player = payload["player"] | |
playerName = str(player.username) | |
message = payload["message"] | |
text = f"[{playerName}] {message}" | |
self.client.loop.call_soon_threadsafe(self.discPlay, text) | |
def discPlay(self, text): | |
asyncio.ensure_future(self.discMessage(text)) | |
async def discMessage(self, text): | |
await self.client.send_message(self.sendChannel, text) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment