Skip to content

Instantly share code, notes, and snippets.

@UnholyGnomes
Created October 3, 2022 19:53
Show Gist options
  • Save UnholyGnomes/c5f437b56b21244af8b454e5d50fc034 to your computer and use it in GitHub Desktop.
Save UnholyGnomes/c5f437b56b21244af8b454e5d50fc034 to your computer and use it in GitHub Desktop.
Rustplus (Beginning)
from email import utils
from importlib.metadata import metadata
from webbrowser import get
import discord
from discord import Embed, Color, Client, File, Intents, Game, Streaming, Activity, ActivityType
from discord.ext import commands, tasks
from discord.ext.commands.bot import Bot
from discord.commands import Option
from discord.ext.commands.context import Context
from rustplus import RustSocket, CommandOptions, Command, ChatEvent, EntityEvent, FCMListener
from colorhash import ColorHash
from io import BytesIO
from datetime import datetime
import os
import json
import rustplus
import traceback
import sys
import math
import requests
import pandas
import random
from dotenv import load_dotenv
from clogging import setup_logger
from clogging import logpath
from clogging import check_if_logger_exists
from selenium import webdriver
import time
import calendar
import asyncio
from datetime import timedelta
from dateutil import tz
import sqlalchemy as db
from sqlalchemy.sql import exists
import discord
load_dotenv()
check_if_logger_exists()
logger = setup_logger('MAIN', logpath)
intents = Intents.all()
PREFIX = os.getenv('PREFIX')
command_options = CommandOptions(os.getenv('PREFIX'))
socket = RustSocket(os.getenv("IP"), os.getenv("PORT"), int(os.getenv("STEAMID")), int(
os.getenv("PLAYERTOKEN")), command_options=command_options, raise_ratelimit_exception=False)
PATH = "C:\Program Files (x86)\chromedriver.exe"
bot = commands.Bot(command_prefix=commands.when_mentioned_or(
f"{PREFIX}"), intents=intents)
engine = db.create_engine(os.getenv("DBPATH"))
connection = engine.connect()
metadata = db.MetaData()
UserData = db.Table('UserData', metadata, autoload=True, autoload_with=engine)
pairedids = db.Table('pairedids', metadata,
autoload=True, autoload_with=engine)
monumentdict = {}
x = 0
async def get_info():
info = await socket.get_info()
return info
async def get_map_markers():
mapmarkers = await socket.get_markers()
return mapmarkers
async def adddone(x):
x += 1
return x
async def chatsend(x):
await socket.send_team_message(x)
async def teamchat():
chats = await socket.get_team_chat()
return chats
async def getmapinfo():
rawmapinfo = await socket.get_raw_map_data()
return rawmapinfo
async def getmonumentinfo():
global mapsize
mapinforreq = await getmapinfo()
monuments = mapinforreq.monuments
for monument in monuments:
monumentdict[monument.token] = {
"x" : monument.x,
"y" : monument.y,
"grid" : await getGrid(monument.x, monument.y, size = mapsize)}
return monumentdict
with open(os.path.join(sys.path[0],"rustplus.py.config.json"), "r") as input_file:
fcm_details = json.load(input_file)
class ServerInfo():
def __init__(self, socket: RustSocket):
self.socket = socket
async def get_info():
return await socket.get_info()
async def get_map_markers():
return await socket.get_markers()
async def get_raw_map_data():
return await socket.get_raw_map_data()
pass
listofids = []
for guild in bot.guilds:
listofids.append(guild.id)
async def get_status(eid:int):
Status = await socket.get_entity_info(eid)
Type = Status.type
return Status.value, Type
async def get_storage_monitor(eid:int):
StorageMonitor = await socket.get_entity_info(eid)
Type = StorageMonitor.type
if Type == 3:
return StorageMonitor.protection_expiry
async def getGrid(loc_x, loc_y, size):
text = ""
x = int(loc_x/146.28571428571428 )
y = int((size-loc_y)/146.28571428571428)
x1 = int(x/26)
x2 = x % 26
if x1 > 0:
for x in range(x1):
text += chr(65+x)
text += chr(65+x2) + str(y)
return str(text)
class RustPlusListener(FCMListener):
chattimes = []
def on_notification(self, obj, notification, data_message):
print(notification)
if notification['data']['channelId'] == 'alarm':
try:
chats = asyncio.run(teamchat())
name = notification['data']['title']
notomessage = notification['data']['message']
message = f"[{name}]: {notomessage}"
tensecondsago = datetime.now() - timedelta(seconds=10)
for chat in chats:
if message == chat.message:
print(len(self.chattimes))
self.chattimes.append(chat.time)
print(self.chattimes)
if len(self.chattimes) == 0:
asyncio.run(chatsend(message))
else:
lastchatsent = datetime.fromtimestamp(self.chattimes[-1:][0])
if lastchatsent < tensecondsago:
asyncio.run(chatsend(message))
pass
except:
print("Error")
if notification['data']['channelId'] == 'pairing':
try:
if notification['data']['message'] == 'Tap to pair with this server.':
return
chats = asyncio.run(teamchat())
body = json.loads(notification['data']['body'])
entid = body['entityId']
message = (f"Notfication sent! Pair with {PREFIX}pair {entid} [name]")
fiveminsago = datetime.now() - timedelta(minutes=5)
for chat in chats:
if message == chat.message:
print(len(self.chattimes))
self.chattimes.append(chat.time)
print(self.chattimes)
if len(self.chattimes) == 0:
asyncio.run(chatsend(message))
else:
lastchatsent = datetime.fromtimestamp(self.chattimes[-1:][0])
if lastchatsent < fiveminsago:
asyncio.run(chatsend(message))
except:
print('Error')
if notification['data']['channelId'] == 'team':
try:
chats = asyncio.run(teamchat())
messagesource = notification['data']['title']
notomessage = notification['data']['message']
message = f"{messagesource}"
tensecondsago = datetime.now() - timedelta(seconds=10)
for chat in chats:
if message == chat.message:
print(len(self.chattimes))
self.chattimes.append(chat.time)
print(self.chattimes)
if len(self.chattimes) == 0:
asyncio.run(chatsend(message))
else:
lastchatsent = datetime.fromtimestamp(self.chattimes[-1:][0])
if lastchatsent < tensecondsago:
asyncio.run(chatsend(message))
pass
except:
print('Error')
# UserData = db.Table('UserData', metadata, autoload=True, autoload_with=engine)
# pairedids = db.Table('pairedids', metadata,
# autoload=True, autoload_with=engine)
class RustCommands(commands.Cog):
def __init__(self, bot: Client, socket: RustSocket):
self.bot: Bot = bot
self.socket = socket
# socket.command(self.broadcast)
socket.command(self.time)
socket.command(self.pop)
socket.command(self.translate)
socket.command(self.day)
socket.command(self.night)
socket.command(self.tog)
socket.command(self.pair)
socket.command(self.unpair)
socket.command(self.promote)
socket.command(self.status)
socket.command(self.upkeep)
socket.command(self.allupkeep)
socket.command(self.getplayerloc)
socket.command(self.offscreen)
socket.command(self.unpairbroken)
socket.command(self.vend)
# async def broadcast(self, command: Command) -> None:
# channel = self.bot.get_channel(int(os.getenv("CHANNEL")))
# await channel.send(embed=Embed(title=f"**From {command.sender_name}:**", description=" ".join(command.args) + "\n\n@everyone", color=Color.from_rgb(*ColorHash(command.sender_name).rgb)))
async def time(self, command: Command) -> None:
time = await self.socket.get_time()
await self.socket.send_team_message(f"Current Time: {time.time}, Sunrise: {time.sunrise}, Sunset: {time.sunset}")
async def pop(self, command: Command) -> None:
serverinfo = await socket.get_info()
await socket.send_team_message(f"There are {serverinfo.players}/{serverinfo.max_players} players online with {serverinfo.queued_players} in que.")
async def translate(self, command: Command) -> None:
option = webdriver.ChromeOptions()
option.add_argument("headless")
driver = webdriver.Chrome(PATH, options=option)
newstring = " ".join(command.args)
driver.get("https://www.google.com/search?q=google+translate&rlz=1C1CHBF_enUS906US906&oq=google+translate&aqs=chrome.0.69i59l2j69i64j69i60l3.4062j0j7&sourceid=chrome&ie=UTF-8")
#time.sleep(1)
Destination = driver.find_element('xpath','//*[@id="tw-source-text-ta"]')
Destination.send_keys(f'{newstring}')
driver.implicitly_wait(2)
translation = driver.find_element('xpath','//*[@id="tw-target-text"]/span')
time.sleep(2)
language = driver.find_element('xpath','//*[@id="tw-sl"]/span[1]').text
language2 = driver.find_element('xpath','//*[@id="tw-tl"]/span[1]').text
await socket.send_team_message(f"Translated {str(language).split(' ')[0]} to {language2} | {translation.text}")
driver.quit()
async def day(self, command: Command) -> None:
daylength = f"{(await socket.get_time()).day_length}"
sunrise = f"{(await socket.get_time()).sunrise}"
sunset = f"{(await socket.get_time()).sunset}"
timenow = f"{(await socket.get_time()).time}"
time_now = await socket.get_time()
hournow = int(timenow.split(":")[0])
minutenow = int(timenow.split(":")[1])
sunsethour = int(sunset.split(":")[0])
sunsetminute = int(sunset.split(":")[1])
sunrisehour = int(sunrise.split(":")[0])
sunriseminute = int(sunrise.split(":")[1])
rl_time_1 = time.time() # This is the current time in seconds
game_time_1 = time_now.raw_time * 60 # This is the current minute count
time.sleep(1)
time_now = await socket.get_time()
# The number of minutes since the last time we checked\watch
game_time_delta = time_now.raw_time * 60 - game_time_1
# The number of seconds since the last time we checked
rl_time_delta = time.time() - rl_time_1
ingameminutestorealsecondsscalar = rl_time_delta/game_time_delta
if hournow > sunrisehour and hournow < sunsethour or hournow == sunrisehour:
print("It is Day...")
timeuntilsunset = timedelta(
hours=sunsethour, minutes=sunsetminute) - timedelta(hours=hournow, minutes=minutenow)
hoursuntilsunset = int(str(timeuntilsunset).split(':')[0])
minutesuntilsunset = int(str(timeuntilsunset).split(':')[1])
print(
f"{hoursuntilsunset} hours and {minutesuntilsunset} minutes until sunset in in game time.")
print(timeuntilsunset)
totalgameminutesuntilsunset = hoursuntilsunset * 60 + minutesuntilsunset
realseconds = totalgameminutesuntilsunset * ingameminutestorealsecondsscalar
print(f"{realseconds} seconds until sunset in real time.")
realtime = f"{int(realseconds / 60)} Minutes and {round(realseconds % 60)} seconds until sunset in real time."
print(realtime)
await socket.send_team_message(realtime)
await asyncio.sleep(2)
if hournow > sunsethour or hournow < sunrisehour or hournow == sunsethour:
print("It is Night...")
timeuntilsunrise = timedelta(
hours=sunrisehour, minutes=sunriseminute) - timedelta(hours=hournow, minutes=minutenow)
# We do this as the timedelta will return a list containing two values if the value is negative. This ensures we only get the positive value (the difference).
ensureweareregettingthetime = (str(timeuntilsunrise).split(',')[-1])
hoursuntilsunrise = int(
str(ensureweareregettingthetime).split(':')[-3])
minutesuntilsunrise = int(
str(ensureweareregettingthetime).split(':')[-2])
print(f"{hoursuntilsunrise} hours and {minutesuntilsunrise} minutes until sunrise in in game time.")
print(timeuntilsunrise)
totalgameminutesuntilsunrise = hoursuntilsunrise * 60 + minutesuntilsunrise
realseconds = totalgameminutesuntilsunrise * ingameminutestorealsecondsscalar
print(f"{realseconds} seconds until sunrise in real time.")
realtime = f"{int(realseconds / 60)} Minutes and {round(realseconds % 60)} seconds until sunrise in real time."
print(realtime)
await socket.send_team_message(realtime)
time.sleep(2)
async def night(self, command: Command) -> None:
daylength = f"{(await socket.get_time()).day_length}"
sunrise = f"{(await socket.get_time()).sunrise}"
sunset = f"{(await socket.get_time()).sunset}"
timenow = f"{(await socket.get_time()).time}"
time_now = await socket.get_time()
hournow = int(timenow.split(":")[0])
minutenow = int(timenow.split(":")[1])
sunsethour = int(sunset.split(":")[0])
sunsetminute = int(sunset.split(":")[1])
sunrisehour = int(sunrise.split(":")[0])
sunriseminute = int(sunrise.split(":")[1])
rl_time_1 = time.time() # This is the current time in seconds
game_time_1 = time_now.raw_time * 60 # This is the current minute count
time.sleep(1)
time_now = await socket.get_time()
# The number of minutes since the last time we checked
game_time_delta = time_now.raw_time * 60 - game_time_1
# The number of seconds since the last time we checked
rl_time_delta = time.time() - rl_time_1
ingameminutestorealsecondsscalar = rl_time_delta/game_time_delta
if hournow > sunrisehour and hournow < sunsethour or hournow == sunrisehour:
print("It is Day...")
timeuntilsunset = timedelta(
hours=sunsethour, minutes=sunsetminute) - timedelta(hours=hournow, minutes=minutenow)
hoursuntilsunset = int(str(timeuntilsunset).split(':')[0])
minutesuntilsunset = int(str(timeuntilsunset).split(':')[1])
print(
f"{hoursuntilsunset} hours and {minutesuntilsunset} minutes until sunset in in game time.")
print(timeuntilsunset)
totalgameminutesuntilsunset = hoursuntilsunset * 60 + minutesuntilsunset
realseconds = totalgameminutesuntilsunset * ingameminutestorealsecondsscalar
print(f"{realseconds} seconds until sunset in real time.")
realtime = f"{int(realseconds / 60)} Minutes and {round(realseconds % 60)} seconds until sunset in real time."
print(realtime)
await socket.send_team_message(realtime)
await asyncio.sleep(2)
if hournow > sunsethour or hournow < sunrisehour or hournow == sunsethour:
print("It is Night...")
timeuntilsunrise = timedelta(
hours=sunrisehour, minutes=sunriseminute) - timedelta(hours=hournow, minutes=minutenow)
# We do this as the timedelta will return a list containing two values if the value is negative. This ensures we only get the positive value (the difference).
ensureweareregettingthetime = (str(timeuntilsunrise).split(',')[-1])
hoursuntilsunrise = int(
str(ensureweareregettingthetime).split(':')[-3])
minutesuntilsunrise = int(
str(ensureweareregettingthetime).split(':')[-2])
print(f"{hoursuntilsunrise} hours and {minutesuntilsunrise} minutes until sunrise in in game time.")
print(timeuntilsunrise)
totalgameminutesuntilsunrise = hoursuntilsunrise * 60 + minutesuntilsunrise
realseconds = totalgameminutesuntilsunrise * ingameminutestorealsecondsscalar
print(f"{realseconds} seconds until sunrise in real time.")
realtime = f"{int(realseconds / 60)} Minutes and {round(realseconds % 60)} seconds until sunrise in real time."
print(realtime)
await socket.send_team_message(realtime)
time.sleep(2)
async def offscreen(self, command: Command) -> None:
try:
teaminfo = await socket.get_team_info()
print(teaminfo)
teamlist = []
for member in teaminfo.members:
grid = await getGrid(member.x, member.y, size = mapsize)
# print(f"[{member.name}][{member.steam_id}][{member.is_online}][{member.x},{member.y}][{grid}]")
teamlist.append(f"[{member.name}][{member.steam_id}][{member.is_online}][{member.x},{member.y}] [{grid}]")
if len(teamlist) > 8:
await chatsend(f"{member.name} | ONLINE? : {member.is_online} | Grid: {grid}")
except:
await socket.send_team_message("No players are offscreen.")
async def tog(self, command: Command) -> None:
try:
if str(command.args[0]).isnumeric():
id = int(command.args[0])
stat = await get_status(id)
print(stat)
if stat[1] == 1:
if stat[0] == False:
await socket.turn_on_smart_switch(id)
await socket.send_team_message("Switch turned on")
elif stat[0] == True:
await socket.turn_off_smart_switch(id)
await socket.send_team_message("Switch turned off")
else:
await socket.send_team_message("This is not a switch")
else:
stmt = db.select(pairedids.c.IdPairedTo).where(pairedids.c.PairedName == command.args[0])
result = connection.execute(stmt)
row = result.fetchone()
print(row)
id = int(row[0])
stat = await get_status(id)
print(stat)
if stat[1] == 1:
if stat[0] == False:
await socket.turn_on_smart_switch(id)
await socket.send_team_message("Switch turned on")
elif stat[0] == True:
await socket.turn_off_smart_switch(id)
await socket.send_team_message("Switch turned off")
else:
await socket.send_team_message("This device is not a switch.")
except:
await socket.send_team_message(f"Device: {command.args[0]} does not exist, please try again.")
async def pair(self, command: Command) -> None:
try:
idtopair = int(command.args[0])
nametopair = command.args[1]
stmt = db.insert(pairedids).values(IdPairedTo=idtopair, PairedName=nametopair)
connection.execute(stmt)
await socket.send_team_message(f"Paired {idtopair} to {nametopair}")
except:
await socket.send_team_message("Error pairing, please try again.")
async def status(self, command: Command) -> None:
try:
if str(command.args[0]).isnumeric():
id = int(command.args[0])
stat = await get_status(id)
if stat[0] == False:
await socket.send_team_message(f"Device: {command.args[0]} is off!")
elif stat[0] == True:
await socket.send_team_message(f"Device: {command.args[0]} is on!")
else:
stmt = db.select(pairedids.c.IdPairedTo).where(
pairedids.c.PairedName == command.args[0])
result = connection.execute(stmt)
row = result.fetchone()
print(row)
id = int(row[0])
stat = await get_status(id)
if stat[0] == False:
await socket.send_team_message(f"Device: {command.args[0]} is off!")
elif stat[0] == True:
await socket.send_team_message(f"Device: {command.args[0]} is on!")
pass
except:
await socket.send_team_message(f"Device: {command.args[0]} does not exist, please try again.")
async def upkeep(self, command: Command) -> None:
try:
if str(command.args[0]).isnumeric():
id = int(command.args[0])
info = await socket.get_entity_info(id)
protection_rem = info.protection_expiry
items = info.items
print(protection_rem, items)
now = time.time()
td = timedelta(seconds=protection_rem - now)
if td < timedelta(0):
await socket.send_team_message(f"Device: {command.args[0]} is DECAYING!")
else:
await socket.send_team_message(f"SMonitor: {command.args[0]} has {str(td).split('.')[0]} left on protection.")
else:
stmt = db.select(pairedids.c.IdPairedTo).where(
pairedids.c.PairedName == command.args[0])
result = connection.execute(stmt)
row = result.fetchone()
print(row)
id = int(row[0])
info = await socket.get_entity_info(id)
protection_rem = info.protection_expiry
items = info.items
print(protection_rem, items)
now = time.time()
td = timedelta(seconds=protection_rem - now)
if td < timedelta(0):
await socket.send_team_message(f"Device: {command.args[0]} is DECAYING!")
else:
await socket.send_team_message(f"SMonitor: {command.args[0]} has {str(td).split('.')[0]} left on protection.")
except:
await socket.send_team_message(f'SMonitor: {command.args[0]} does not exist, please try again.')
async def allupkeep(self, command: Command) -> None:
try:
stmt = db.select(pairedids.c.IdPairedTo, pairedids.c.PairedName)
result = connection.execute(stmt)
for row in result:
try:
id = int(row[0])
name = row[1]
info = await socket.get_entity_info(id)
print(info.type)
if info.type == 3:
protection_rem = info.protection_expiry
items = info.items
print(protection_rem, items)
now = time.time()
td = timedelta(seconds=protection_rem - now)
if td < timedelta(0):
await socket.send_team_message(f"Device: {name} is DECAYING!")
else:
await socket.send_team_message(f"SMonitor: {name} has {str(td).split('.')[0]} left on protection.")
except rustplus.RequestError:
pass
except:
await socket.send_team_message(f'UpKeepAll: Error.')
async def unpair(self, command: Command) -> None:
try:
stmt = db.delete(pairedids).where(pairedids.c.PairedName == command.args[0])
connection.execute(stmt)
await socket.send_team_message(f"Unpaired {command.args[0]}")
except:
await socket.send_team_message(f"Could not unpair {command.args[0]}. Possibly not paired?")
async def promote(self, command: Command) -> None:
try:
team = await socket.get_team_info()
for member in team.members:
if " ".join(command.args).lower() == member.name.lower():
playername = member.name
playerid = member.steam_id
print(playername, playerid)
if playerid == team.leader_steam_id:
await socket.send_team_message(f"{playername} is already the leader!")
raise Exception
else:
await socket.promote_to_team_leader(playerid)
newteam = await socket.get_team_info()
if newteam.leader_steam_id == playerid:
await socket.send_team_message(f"{playername} has been promoted to team leader!")
else:
await socket.send_team_message(f"Could not promote {playername} to team leader.")
except:
pass
async def getplayerloc(self, command: Command) -> None:
try:
if str(command.args[0]).isnumeric():
id = int(command.args[0])
info = await socket.get_team_info()
for member in info.members:
if member.steam_id == id:
grid = await getGrid(member.x, member.y, size = mapsize)
await socket.send_team_message(f"Player: {member.name} is at {grid}.")
else:
info = await socket.get_team_info()
for member in info.members:
if " ".join(command.args).lower() == member.name.lower():
print(member.name.lower())
grid = await getGrid(member.x, member.y, size = mapsize)
await socket.send_team_message(f"Player: {member.name} is at {grid}.")
except:
await socket.send_team_message(f"Device: {command.args[0]} does not exist, please try again.")
async def unpairbroken(self, command: Command) -> None:
try:
stmt = db.select(pairedids.c.IdPairedTo, pairedids.c.PairedName)
result = connection.execute(stmt)
for row in result:
try:
id = int(row[0])
name = row[1]
info = await socket.get_entity_info(id)
except rustplus.RequestError:
stmt = db.delete(pairedids).where(pairedids.c.PairedName == name)
connection.execute(stmt)
await socket.send_team_message(f"Unpaired {name}!")
except:
await socket.send_team_message(f"UnpairBroken: Error.")
async def vend(self, command: Command) -> None:
mapmarkers = await socket.get_markers()
markersdict = {}
d = {}
wb = pandas.read_excel(os.path.join(sys.path[0], 'RustItemIDS.xlsx'))
itemrequested = " ".join(command.args)
print(itemrequested)
resultslist = []
for marker in mapmarkers:
orderslist = []
orderstrings = []
markersdict[marker.id] = {
"id": marker.id,
"type": marker.type,
"name": marker.name,
"x": marker.x,
"y": marker.y,
"rotation": marker.rotation,
"grid": await getGrid(marker.x, marker.y, mapsize),
"sell_orders": marker.sell_orders,
"ordershere": orderslist,
"orderstrings": orderstrings
}
for order in marker.sell_orders:
markerid = marker.id
grid = await getGrid(marker.x, marker.y, mapsize)
itemrow = wb.loc[wb['Item ID'] == order.item_id]
itemnametobuy = itemrow['Display Name'].values[0]
itemid = order.item_id
quantityofitemtobuy = order.quantity
itemtopayrow = wb.loc[wb['Item ID'] == order.currency_id]
item_to_payname = itemtopayrow['Display Name'].values[0]
item_to_payid = order.currency_id
item_to_paynumberofitem = order.cost_per_item
item_is_bp = order.item_is_blueprint
currency_is_bp = order.currency_is_blueprint
amount_in_stock = order.amount_in_stock
if int(amount_in_stock) >= 1:
orderslist.append([markerid, grid, str(itemnametobuy).lower(), itemid, quantityofitemtobuy, item_to_payname,
item_to_payid, item_to_paynumberofitem, item_is_bp, currency_is_bp, amount_in_stock])
orderstrings.append(
f"{str(itemnametobuy).lower()}:{grid} | {quantityofitemtobuy} {itemnametobuy} for {item_to_paynumberofitem} {item_to_payname} | {amount_in_stock} in stock")
for x in markersdict:
if any(str(itemrequested).lower() in str(s).lower() for s in markersdict[x]['orderstrings']):
newlist = markersdict[x]['orderstrings']
for x in newlist:
if itemrequested in x:
resultslist.append(x)
if len(resultslist) == 0:
await socket.send_team_message(f"No results found for {itemrequested}.")
else:
await socket.send_team_message(f"{len(resultslist)} results found for {itemrequested}.")
for x in resultslist:
y = str(x).split(':')[1:]
await socket.send_team_message(''.join(y))
class DiscordRustCommands(commands.Cog):
def __init__(self, bot, socket: RustSocket):
self.bot: Bot = bot
self.socket = socket
try:
@bot.slash_command(pass_context=True,name='time', description='Shows the in game time!')
async def time(ctx : discord.ApplicationContext):
time = await socket.get_time()
await ctx.respond(embed=Embed(title=f"It is currently {time.time} in-game", description=f"Sunrise is at {time.sunrise} and Sunset at {time.sunset}", color=Color.from_rgb(*ColorHash(time.time).rgb)))
@bot.slash_command(pass_context=True, description='Shows all paired TC upkeeps!')
async def allupkeep(ctx: discord.ApplicationContext):
try:
stmt = db.select(pairedids.c.IdPairedTo, pairedids.c.PairedName)
result = connection.execute(stmt)
strings = []
await ctx.defer(ephemeral=True)
for row in result:
try:
id = int(row[0])
name = row[1]
info = await socket.get_entity_info(id)
print(info.type)
if info.type == 3:
protection_rem = info.protection_expiry
items = info.items
print(protection_rem, items)
now = time.time()
td = timedelta(seconds=protection_rem - now)
if td < timedelta(0):
string = f"**{name}** is *DECAYING*!."
else:
string = f"**{name}** has *{str(td).split('.')[0]}* left on protection."
strings.append(string)
else:
pass
except rustplus.RequestError:
pass
await ctx.respond(embed=Embed(title=f"All Paired TC Upkeeps", description="\n".join(strings), color=Color.from_rgb(*ColorHash(str(random.randint(1, 256))).rgb)))
except:
await ctx.respond(embed=Embed(title=f'UpKeepAll: Error.', color=Color.from_rgb(*ColorHash(str(name)).rgb)))
@bot.slash_command(pass_context=True, description='Shows the in game map!')
async def map(ctx: discord.ApplicationContext):
await ctx.defer(ephemeral=True)
map = await socket.get_map(True, True, False)
with BytesIO() as image_binary:
map.save(image_binary, 'PNG')
image_binary.seek(0)
await ctx.respond(file=File(fp=image_binary, filename="map.png"))
@bot.slash_command(pass_context=True, description='Shows the current team!')
async def team(ctx: discord.ApplicationContext):
team_info = await socket.get_team_info()
for member in team_info.members:
if member.steam_id == team_info.leader_steam_id:
leader = member
leadername = leader.name
break
# await ctx.send(embed=Embed(title=f"Info for {leader.name}'s team:", description="\n".join([f"**{player.name}:** | Online: {player.is_online} | Alive: {player.is_alive}" for player in team_info.members]), color=Color.from_rgb(*ColorHash(leader.name).rgb)))
embed = Embed(title=f"Info for {leadername}'s team:", description="\n".join([f"**{player.name}:** | Online: {player.is_online} | Alive: {player.is_alive} | Location: {await getGrid(player.x,player.y, size = mapsize)}" for player in team_info.members]), color=Color.from_rgb(*ColorHash(leadername).rgb))
embed.set_thumbnail(url='https://i.pinimg.com/236x/f1/a2/aa/f1a2aaf9ebeed8d37a571b4ca485d981.jpg')
await ctx.respond(embed=embed)
@bot.slash_command(pass_context=True, description='Toggle paired smart switches!')
async def tog(ctx: discord.ApplicationContext, device: Option(str, 'Enter the name of the device to toggle!', required=True)):
try:
if str(device).isnumeric():
id = int(device)
stat = await get_status(id)
print(stat)
if stat[1] == 1:
if stat[0] == False:
await socket.turn_on_smart_switch(id)
await socket.send_team_message("Switch turned on")
await ctx.respond("Switch turned on")
elif stat[0] == True:
await socket.turn_off_smart_switch(id)
await socket.send_team_message("Switch turned off")
await ctx.respond("Switch turned off")
else:
await ctx.respond("This device is not a switch")
else:
stmt = db.select(pairedids.c.IdPairedTo).where(
pairedids.c.PairedName == device)
result = connection.execute(stmt)
row = result.fetchone()
print(row)
id = int(row[0])
stat = await get_status(id)
print(stat)
if stat[1] == 1:
if stat[0] == False:
await socket.turn_on_smart_switch(id)
await socket.send_team_message("Switch turned on")
await ctx.respond("Switch turned on")
elif stat[0] == True:
await socket.turn_off_smart_switch(id)
await socket.send_team_message("Switch turned off")
await ctx.respond("Switch turned off")
else:
await ctx.respond("This device is not a switch.")
except:
await socket.send_team_message(f"Device: {device} does not exist, please try again.")
@bot.slash_command(pass_context=True, description='Show the status of any paired switch!')
async def status(ctx: discord.ApplicationContext, name: Option(str, 'Enter the name of the device the check the status of!', required=True)):
try:
if str(name).isnumeric():
id = int(name)
stat = await get_status(id)
if stat[0] == False:
await ctx.respond(f"Device: {name} is off!")
elif stat[0] == True:
await ctx.respond(f"Device: {name} is on!")
else:
stmt = db.select(pairedids.c.IdPairedTo).where(
pairedids.c.PairedName == name)
result = connection.execute(stmt)
row = result.fetchone()
print(row)
id = int(row[0])
stat = await get_status(id)
if stat[0] == False:
await ctx.respond(f"Device: {name} is off!")
elif stat[0] == True:
await ctx.respond(f"Device: {name} is on!")
pass
except:
await socket.send_team_message(f"Device: {name} does not exist, please try again.")
@bot.slash_command(pass_context=True, description='Promote a player to the team leader in game!')
async def promote(ctx: discord.ApplicationContext, name: Option(str, 'Enter the name of the player to be promoted!', required=True)):
try:
team = await socket.get_team_info()
for member in team.members:
if str(name).lower() == member.name.lower():
playername = member.name
playerid = member.steam_id
print(playername, playerid)
if playerid == team.leader_steam_id:
await socket.send_team_message(f"{playername} is already the leader!")
raise Exception
else:
await socket.promote_to_team_leader(playerid)
newteam = await socket.get_team_info()
if newteam.leader_steam_id == playerid:
await socket.send_team_message(f"{playername} has been promoted to team leader!")
await ctx.respond(f"{playername} has been promoted to team leader!")
else:
await socket.send_team_message(f"Could not promote {playername} to team leader.")
await ctx.respond(f"Could not promote {playername} to team leader.")
except Exception:
print(traceback.format_exc())
pass
@bot.slash_command(pass_context=True, description='Show the upkeep of any paired TC!')
async def upkeep(ctx: discord.ApplicationContext, toolcabinet: Option(str, 'Enter the name or ID of the tool cabinet to be checked!', required=True)):
try:
if str(toolcabinet).isnumeric():
id = int(toolcabinet)
info = await socket.get_entity_info(id)
protection_rem = info.protection_expiry
items = info.items
print(protection_rem, items)
now = time.time()
td = timedelta(seconds=protection_rem - now)
await ctx.respond(embed=Embed(title=f"SMonitor: {toolcabinet} has {str(td).split('.')[0]} left on protection.", color=Color.from_rgb(*ColorHash(str(toolcabinet)).rgb)))
else:
stmt = db.select(pairedids.c.IdPairedTo).where(
pairedids.c.PairedName == toolcabinet)
result = connection.execute(stmt)
row = result.fetchone()
print(row)
id = int(row[0])
info = await socket.get_entity_info(id)
protection_rem = info.protection_expiry
items = info.items
print(protection_rem, items)
now = time.time()
td = timedelta(seconds=protection_rem - now)
await ctx.respond(embed=Embed(title=f"SMonitor: {toolcabinet} has {str(td).split('.')[0]} left on protection.", color=Color.from_rgb(*ColorHash(str(toolcabinet)).rgb)))
except:
await ctx.respond(embed=Embed(title=f'SMonitor: {toolcabinet} does not exist, please try again.', color=Color.from_rgb(*ColorHash(str(toolcabinet)).rgb)))
# @commands.command()
# async def buttons(ctx):
# stmt = db.select(pairedids.c.IdPairedTo, pairedids.c.PairedName)
# result = connection.execute(stmt)
# for row in result:
# entid = int(row[0])
# name = row[1]
# try:
# info = await socket.get_entity_info(entid)
# if info.type == 1:
# embed = Embed(title=f"Device: {name}.", color=Color.from_rgb(*ColorHash(name).rgb))
# embed.set_thumbnail(
# url='https://lh6.googleusercontent.com/bzlmBpUHLkb48ejlCaPuHetPFeMq3xuPZORbP4V8nrDIwjRm4Epp5Qu5z2VhKNdqNv2_w_j-vW37tUvEOKR5dyo=w1280')
# await ctx.send(embed=embed)
# await ctx.send(view=MyView(name, entid, socket))
# except rustplus.RequestError:
# pass
except:
pass
class TCTracker(commands.Cog):
def __init__(self, bot, socket):
self.bot = bot
self.socket = socket
self.TCTRacker = discord.Embed(
title = "__**Test Embed Rules**__",
description = ""
)
self.UpdateTCTracker.start()
@commands.command()
@commands.is_owner()
async def TCTrackerSetup(self,ctx):
channel = bot.get_channel(int(os.getenv("TRACKERCHANNEL")))
await channel.send(embed=self.TCTRacker)
@tasks.loop(seconds=300)
async def UpdateTCTracker(self):
try:
channel = bot.get_channel(int(os.getenv("TRACKERCHANNEL")))
msg = await channel.fetch_message(1008813919961370666)
stmt = db.select(pairedids.c.IdPairedTo, pairedids.c.PairedName)
result = connection.execute(stmt)
from_zone = tz.tzutc()
to_zone = tz.tzlocal()
utc = datetime.utcnow()
utc = utc.replace(tzinfo=from_zone)
timeupdated = utc.astimezone(to_zone)
strings = []
for row in result:
try:
id = int(row[0])
name = row[1]
info = await socket.get_entity_info(id)
print(info.type)
if info.type == 3:
protection_rem = info.protection_expiry
items = info.items
print(protection_rem, items)
now = time.time()
td = timedelta(seconds=protection_rem - now)
if td < timedelta(0):
string = f"**{name}** is *DECAYING*!."
else:
string = f"**{name}** has *{str(td).split('.')[0]}* left on protection."
strings.append(string)
except rustplus.RequestError as e:
try:
info
if info.type == 3:
pass
else:
pass
except NameError:
pass
print(e)
pass
else:
pass
strings.insert(0,f"Last Updated: <t:{calendar.timegm(timeupdated.utctimetuple())}:R>\n")
newembed = discord.Embed(title=f"All Paired TC Upkeeps", description="\n".join(
strings), color=Color.from_rgb(*ColorHash(str(random.randint(1, 256))).rgb))
await msg.edit(embed=newembed)
except Exception as e:
print(e)
print(traceback.format_exc())
pass
# await ctx.send(embed=Embed(title=f'UpKeepAll: Error.', color=Color.from_rgb(*ColorHash(str(name)).rgb)))
# @commands.command()
# @commands.is_owner()
# async def tctrackerupdate(self, bot: Bot, ctx: Context, text):
# try:
# stmt = db.select(pairedids.c.IdPairedTo, pairedids.c.PairedName)
# result = connection.execute(stmt)
# strings = []
# for row in result:
# id = int(row[0])
# name = row[1]
# info = await socket.get_entity_info(id)
# print(info.type)
# if info.type == 3:
# protection_rem = info.protection_expiry
# items = info.items
# print(protection_rem, items)
# now = time.time()
# td = timedelta(seconds=protection_rem - now)
# if td < timedelta(0):
# string = f"**{name}** is *DECAYING*!."
# else:
# string = f"**{name}** has *{str(td).split('.')[0]}* left on protection."
# strings.append(string)
# else:
# pass
# except:
# pass
# await ctx.send(embed=Embed(title=f'UpKeepAll: Error.', color=Color.from_rgb(*ColorHash(str(name)).rgb)))
# await ctx.send(embed=Embed(title=f"All Paired TC Upkeeps", description="\n".join(strings), color=Color.from_rgb(*ColorHash(str(random.randint(1, 256))).rgb)))
class RustDiscordChannel(commands.Cog):
def __init__(self, bot, socket: RustSocket):
self.bot = bot
self.socket = socket
self.socket.chat_event(self.rust_chat_listener)
async def rust_chat_listener(self, event: ChatEvent):
channel = self.bot.get_channel(int(os.getenv("CHANNEL")))
await channel.send(f"[{datetime.utcfromtimestamp(event.message.time).strftime('%H:%M')}] {event.message.name}: {event.message.message}")
@tasks.loop(seconds=30)
async def randomstatus():
rng = random.randint(1, 4)
logger.info(f"Changing status...")
logger.info(f"Random status is {rng}")
if rng == 1:
logger.info(f'Setting status to "Playing Amogus? :amogusemoji:"')
await bot.change_presence(activity=Game(name="Amogus? ඞ"))
if rng == 2:
logger.info(f'Setting status to "Streaming "Not actually streaming""')
await bot.change_presence(activity=Streaming(name="Not actually streaming", url="https://www.twitch.tv/twitch"))
if rng == 3:
logger.info(f'Setting status to "Listening to Godzilla!"')
await bot.change_presence(activity=Activity(type=ActivityType.listening, name="Godzilla!"))
if rng == 4:
logger.info(
f'Setting status to "Watching https://github.com/UnholyGnomes/Gnome-Bot/"')
await bot.change_presence(activity=Activity(type=ActivityType.watching, name="https://github.com/UnholyGnomes/Gnome-Bot/"))
class DiscordMirror(commands.Cog):
def __init__(self, bot, socket: RustSocket):
self.bot = bot
self.socket = socket
@bot.event
async def on_message(message):
channel = bot.get_channel(int(os.getenv("CHANNEL")))
if message.channel == channel:
if message.author.id != 931357215690997849:
if message.author.nick == None:
string2 = str(message.author.name)
else:
string2 = str(message.author.nick)
string1 = str(message.content)
await socket.send_team_message(f'{string2}: {string1}')
@tasks.loop(seconds=10)
async def eventcheck():
print(monumentdict['oil_rig_small'])
oilrigsmallx = monumentdict['oil_rig_small']['x']
oilrigsmally = monumentdict['oil_rig_small']['y']
oilrigsmallgrid = monumentdict['oil_rig_small']['grid']
print(oilrigsmallx, oilrigsmally, oilrigsmallgrid)
oilriglargex = monumentdict['large_oil_rig']['x']
oilriglargey = monumentdict['large_oil_rig']['y']
oilriglargegrid = monumentdict['large_oil_rig']['grid']
print(oilriglargex, oilriglargey, oilriglargegrid)
launchx = monumentdict['launchsite']['x']
launchy = monumentdict['launchsite']['y']
launchgrid = monumentdict['launchsite']['grid']
print(launchx, launchy, launchgrid)
for event in await socket.get_current_events():
if event.type == 2:
print(event)
launchcords = (launchx, launchy)
eucdistancelaunch = math.dist(launchcords, (event.x, event.y))
print(eucdistancelaunch)
if eucdistancelaunch < 200:
print("Bradley has been taken!")
else:
print(f'Heli taken at {await getGrid(event.x,event.y, size = mapsize)}')
if event.type == 4:
print(event)
cargohelicords = (event.x, event.y)
print(f'CargoHeli at {await getGrid(cargohelicords[0],cargohelicords[1], size = mapsize)}')
if event.type == 5:
print(event)
cargocords = event.x, event.y
print(f'CargoShip at {await getGrid(cargocords[0],cargocords[1], size = mapsize)}')
if event.type == 6:
loilcords = (oilriglargex, oilriglargey)
soilcords = (oilrigsmallx, oilrigsmally)
cratecords = (event.x, event.y)
eucdistancelarge = math.dist(loilcords, cratecords)
eucdistancesmall = math.dist(soilcords, cratecords)
if eucdistancelarge < 50:
print(f'Crate is at large oil rig')
elif eucdistancesmall < 50:
print(f'Crate is at small oil rig')
try:
if cargocords:
eucdistancecargo = math.dist(cargocords, cratecords)
if eucdistancecargo < 50:
print(f'Crate is at cargo ship')
except:
pass
# elif eucdistancecargo < 50:
# print(f'Crate is at cargo ship')
print(f'Crate at {await getGrid(event.x,event.y, size = mapsize)}')
@bot.event
async def on_ready():
await socket.connect()
logger.info(f"We have logged in as {bot.user}")
logger.info('Bot is ready!')
logger.info(f"This bot is active in {len(bot.guilds)} guild(s).")
logger.info(f"- - - SERVER LIST - - -")
for guild in bot.guilds:
logger.info(f"Server {guild.id} : {guild.name}")
RustPlusListener(fcm_details).start(False)
bot.add_cog(RustCommands(bot, socket))
bot.add_cog(RustDiscordChannel(bot, socket))
bot.add_cog(TCTracker(bot, socket))
bot.add_cog(DiscordMirror(bot, socket))
global mapsize
info = await ServerInfo.get_info()
mapsize = info.size
stmt = db.select(UserData).where(UserData.c.SteamID == int(os.getenv("STEAMID")))
print(os.getenv("STEAMID"))
randomstatus.start()
resultprox = connection.execute(stmt)
resultset = resultprox.fetchall()
if len(resultset) == 0:
stmt = db.insert(UserData).values(SteamID=int(os.getenv("STEAMID")))
connection.execute(stmt)
bot.add_cog(DiscordRustCommands(bot, socket))
bot.run(os.getenv("TOKEN"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment