Last active
May 14, 2019 20:07
-
-
Save FranchuFranchu/0ac6dcefda2c3549324a4ae2d228f5a3 to your computer and use it in GitHub Desktop.
28/04 edition of TalvorGames' bot
This file contains hidden or 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 asyncio import coroutine | |
import asyncio | |
import socket | |
import sys | |
import discord | |
from discord.ext import commands | |
import random | |
from multiprocessing import Manager | |
from multiprocessing.dummy import Process | |
try: | |
import discord.abc | |
except ImportError: | |
print('ERROR: You must use Rewrite branch, not async') | |
else: | |
print('Using rewrite branch of discordpy') | |
import time | |
import datetime | |
description = '''The bot of teh server''' | |
curr_working_channel = None | |
name = "mcbot" | |
token = "NTcxNzY0ODY4NDM3NTA4MTM2.XMXzgw.14BqjOp3QLsKap0vDqtEJE5eyxU" | |
port = 32165 | |
ip = "127.0.0.1" | |
CHANGE_CHANNEL_MESSAGE = 'change-channel' | |
import discord | |
import asyncio | |
class MyClient(commands.Bot): | |
def __init__(self, *args, **kwargs): | |
super().__init__(*args, **kwargs) | |
# create the background task and run it in the background | |
self.n = 0 | |
self.clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
self.clientsocket.connect((ip,port)) | |
print('Connected to {}:{}'.format(ip,str(port))) | |
self.clientsocket.setblocking(False) | |
def __str__(): | |
return "Bot "+self.user.name | |
__repr__ = __str__ | |
async def parse_msg_txt(self,channel,i): | |
if i.startswith('@'): | |
m = await get_user_by_name(channel,i[1:]) | |
if m == None: | |
return i | |
else: | |
return m.mention | |
async def on_ready(self): | |
print('Logged in as') | |
print(self.user.name) | |
print(self.user.id) | |
print('------') | |
self.bg_task = self.loop.create_task(self.my_background_task()) | |
async def on_message(self,message): | |
await super().on_message(message) | |
if message.content.startswith('mc '): | |
return | |
with open('.{}-channel'.format(name),'r') as f: | |
curr_working_channel = self.get_channel(int(f.read())) | |
if message.content == CHANGE_CHANNEL_MESSAGE: | |
with open('.{}-channel'.format(name),'w') as f: | |
f.write(str(message.channel.id)) | |
print('Channel changed, now it is #{}: ID {}'.format(str(message.channel),str(message.channel.id))) | |
elif message.content.startswith('mc kick'): | |
pass | |
elif message.channel == curr_working_channel and message.author != self.user: | |
print('Discord message detected: '+message.content) | |
t = bytes(str(message.author),'ascii')+b'\x00'+bytes(message.content,'ascii') | |
print('Sending '+repr(t)+' to Minecraft server') | |
self.clientsocket.sendall(len(t).to_bytes(2, byteorder='little')+b'\x01'+t) | |
async def my_background_task(self): | |
if self.ws == None: | |
self.bg_task.cancel() | |
print('Closing socket...') | |
self.clientsocket.close() | |
return | |
try: | |
x = self.clientsocket.recv(2) | |
except BlockingIOError: | |
print('\r',end='') | |
sys.stdout.flush() | |
print('Waiting for Minecraft message... {}s'.format(str(self.n)),end='') | |
sys.stdout.flush() | |
await asyncio.sleep(1) | |
self.n += 1 | |
else: | |
print('\n') | |
self.n = 0 | |
print('Message received from Minecraft!') | |
msg_type = self.clientsocket.recv(1) | |
print('Packet length: '+str(int.from_bytes(x,byteorder="little"))) | |
print('Packet type: '+str(msg_type)) | |
x = self.clientsocket.recv(int.from_bytes(x,byteorder="little")) | |
print('Packet data: '+str(x)) | |
try: | |
with open('.{}-channel'.format(name),'r') as f: | |
curr_working_channel = self.get_channel(int(f.read())) | |
except FileNotFoundError: | |
curr_working_channel = None | |
print('Will send message to #'+str(curr_working_channel)) | |
if curr_working_channel != None: | |
x = str(x)[2:-1] | |
print('..') | |
# Used to mention people, not working (yet)#x = ' '.join([await parse_msg_txt(curr_working_channel,i) for i in x.split(' ')]) | |
self.loop.create_task(curr_working_channel.send(x)) | |
self.bg_task = self.loop.create_task(self.my_background_task()) | |
bot = MyClient(command_prefix='mc ', description=description) | |
short_map = { | |
"d":"days", | |
"s":"seconds", | |
"z":"microseconds", | |
"x":"milliseconds", | |
"y":"years", | |
"h":"hours", | |
"w":"weeks", | |
} | |
async def get_user_by_name(msg,channel): | |
for i in channel.guild.members: | |
if (i.display_name == name): | |
return i | |
return None | |
@bot.command(pass_context=True) | |
async def ban(ctx,player,time,reason): | |
print(list(filter(lambda i: str(i) == "can_ban",ctx.message.author.roles))) | |
if not len(list(filter(lambda i: str(i) == "can_ban",ctx.message.author.roles))) > 0: | |
await ctx.get_user(ctx.message.author.id).create_dm() | |
await ctx.bot.send_message(ctx.bot.get_user(ctx.message.author.id).dm_channel,"No permission!") | |
return | |
if time != 'perm': | |
curr = datetime.timedelta() | |
currt = "z" | |
curri = "0" | |
for i in time: | |
if i.isdigit(): | |
curri+=i | |
else: | |
curr += datetime.timedelta(**{short_map[i]:int(curri)}) | |
currt = 0 | |
curri = "0" | |
else: | |
curr = datetime.timedelta(weeks=-10) | |
print((datetime.datetime.utcnow() + curr).isoformat()) | |
t = (bytes(str(ctx.author),'ascii') | |
+ b'\x00'+bytes(str(player),'ascii') | |
+ b'\x00'+bytes((datetime.datetime.utcnow() + curr).isoformat(),"ascii") | |
+ b'\x00'+bytes(reason,'ascii')) | |
print(t) | |
bot.clientsocket.sendall(len(t).to_bytes(2, byteorder='little')+b'\x10'+t) | |
@bot.command(pass_context=True) | |
async def mute(ctx,player,time,reason): | |
if time != 'perm': | |
curr = datetime.timedelta() | |
currt = "z" | |
curri = "0" | |
for i in time: | |
if i.isdigit(): | |
curri+=i | |
else: | |
curr += datetime.timedelta(**{short_map[i]:int(curri)}) | |
currt = 0 | |
curri = "0" | |
else: | |
curr = datetime.timedelta(weeks=-10) | |
print((datetime.datetime.utcnow() + curr).isoformat()) | |
t = (bytes(str(ctx.author),'ascii') | |
+ b'\x00'+bytes(str(player),'ascii') | |
+ b'\x00'+bytes((datetime.datetime.utcnow() + curr).isoformat(),"ascii") | |
+ b'\x00'+bytes(reason,'ascii')) | |
print(t) | |
bot.clientsocket.sendall(len(t).to_bytes(2, byteorder='little')+b'\x11'+t) | |
def bot_main(): | |
print('Bot is starting up...') | |
bot.run(token) | |
if __name__ == '__main__': | |
#Process(target=bot_main).start() | |
bot_main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment