Beispiel #1
0
async def delete_interval(ctx, name: str = ""):
    global mapi
    global f_updated
    server = ServerInterface(mapi, ctx.guild.id)

    if not await is_admin(ctx):
        return None

    if name == "":
        await ctx.send(f"You have to set a interval to delete.")
        return None

    try:
        qi.delete_intervals(mapi, ctx.guild.id, name)
    except ConnectionError as excep:
        logging.exception(excep)
        await ctx.send(f"{name} is not a valid id.")
        return None

    ids = server.interval_ids
    if name != "*":
        ids.remove(int(name))
        server.interval_ids = ids
    else:
        server.interval_ids = []

    f_updated = True

    await ctx.send("Deleted the interval(s)")
Beispiel #2
0
async def insult(ctx):
    """
    Insults the user back.

    :param ctx: context of the command to which the bot is responding
    :return:
    """

    global mapi
    server = ServerInterface(mapi, ctx.guild.id)
    nsfw = False
    try:
        server = ServerInterface(mapi, ctx.guild.id, ctx.guild.name)
        nsfw = server.nsfw
    except ConnectionError as ex:
        logging.exception(ex)

    if not nsfw:
        await ctx.send(
            "Error. Please enable NSFW content on your server, with 'option NSFW true'"
        )
        return None

    insults = ("Well f**k you too.", "You dirty m**********r.",
               f"You are so friendly {str(ctx.author).split('#')[0]}",
               "You bloody wanker.", "You are like a dog with two dicks",
               "Dickhead", "Twat", "Suck my chungus",
               "I'm gonna leave soon...", "Get lost")

    fuck_you = random.choice(insults)
    await ctx.send(fuck_you)
Beispiel #3
0
async def on_guild_join(guild):
    global mapi
    try:
        ServerInterface(mapi, guild.id, guild.name)

    except ConnectionError as excep:
        logging.exception(excep)

    logging.info(f"[{guild.id}] Added to server")
Beispiel #4
0
def get_prefix(client, message):
    global mapi
    try:
        server = ServerInterface(mapi, message.guild.id, message.guild.name)
        return server.prefix

    except ConnectionError as ex:
        logging.exception(ex)
        return "$"
Beispiel #5
0
 def enterTheGame(self):
     self.error_label.hide()
     self.name = self.nameEdit.text()
     if not self.nameValidation(self.name):
         return
     self.server_interface = ServerInterface(self.nameEdit.text())
     self.database = ServerData()
     self.updateData()
     self.graphWidget.setGraph(self.database.getGraph())
     self.bot = Bot(self.server_interface, self.database, self)
     self.bot.start()
    def __init__(self, name, callback=None):
        self._name = name
        self._server = ServerInterface()
        self._order_procs = []
        self.order_N = 0

        self._proc_manager = Manager()
        self._proc_return_dict = self._proc_manager.dict()

        self.cash = 0

        if callback is None:
            self._callback = lambda trader, entry: None
        else:
            self._callback = callback

        self._positions = {
            "SP-FUTURE":0,
            "ESX-FUTURE":0
        }
Beispiel #7
0
async def change_prefix(ctx, prefix):
    """
    Changes the prefix used to summon the bot.

    :param ctx: context
    :param prefix: new prefix
    :return:
    """
    global mapi

    if not await is_admin(ctx):
        return None

    server = ServerInterface(mapi, ctx.guild.id)

    if prefix == server.prefix:
        await ctx.send(f"Prefix was already set to {prefix}.")
        return None
    server.prefix = prefix

    await ctx.send(f"Changed prefix to {prefix}")
Beispiel #8
0
async def set_option(ctx, name: str = "", value: str = ""):
    """
        Changes a option of the bot.

        :param ctx: context
        :param name: name of the option
        :param value: value of the option
        :return:
    """

    global mapi

    if not await is_admin(ctx):
        return None

    name_options = ["NSFW", "changePrefix"]

    if name not in name_options:
        await ctx.send("This is not a option that can be set.")
        return None

    if name == "changePrefix":
        await change_prefix(ctx, value)
    else:
        server = ServerInterface(mapi, ctx.guild.id)
        value = value.lower()
        value_options = ['true', 'false']
        if value not in value_options:
            await ctx.send("Could not recognize value")
            return None
        value = bool(value == "true")

        if value == server.nsfw:
            await ctx.send(f"{name} was already set to {value}")
            return None

        server.nsfw = value
        await ctx.send(f"{name} updated to {value}")
Beispiel #9
0
    def enterTheGame(self):
        self.error_label.hide()
        self.name = self.nameEdit.text()
        if not self.nameValidation(self.name):
            return
        ServerInterface(self.nameEdit.text())
        self.database = ServerData()

        try:
            self.graphWidget.setWeightLabelsVisible(False)
            self.graphWidget.setGraph(self.database.getGraph())
            self.graphWidget.setBuildings(self.database.getBuildings())
        except TypeError as error_:
            self.error_label(str(error_))
Beispiel #10
0
from server_interface import ServerInterface
import numpy as np
import time
interface = ServerInterface()
name = "cookie_sophisticated_2"

percentage_bought_threshold = 0.7
risk_factor = 0.2

current_market = {"SP-FUTURE": None, "ESX-FUTURE": None}

old_market = {"SP-FUTURE": None, "ESX-FUTURE": None}
trade = None


def callback(entry):
    global trade

    #print(entry)
    if entry['TYPE'] == 'PRICE':
        #print(trade)
        # Update market variables
        old_market[entry['FEEDCODE']] = current_market[entry['FEEDCODE']]
        current_market[entry['FEEDCODE']] = entry

        # Check if data available
        for key in old_market.keys():
            if old_market[key] is None:
                print("returning")
                return
from server_interface import ServerInterface

if __name__ == "__main__":
    server = ServerInterface()
    server.main()
class Trader:
    def __init__(self, name, callback=None):
        self._name = name
        self._server = ServerInterface()
        self._order_procs = []
        self.order_N = 0

        self._proc_manager = Manager()
        self._proc_return_dict = self._proc_manager.dict()

        self.cash = 0

        if callback is None:
            self._callback = lambda trader, entry: None
        else:
            self._callback = callback

        self._positions = {
            "SP-FUTURE":0,
            "ESX-FUTURE":0
        }

    def buy(self, feedcode, amount):
        def fn(server, name, feedcode, amount, return_dict, order_N):
            return_dict[order_N] = server.buy(name, feedcode, 10000, np.ceil(amount).astype(int))
        proc =  Process(target=fn, args = (self._server, self._name, feedcode, amount, self._proc_return_dict, self.order_N))
        print(self.order_N, "BUY", feedcode, amount)
        self._order_procs.append((self.order_N, proc));
        self.order_N += 1
        proc.start()

    def sell(self, feedcode, amount):
        def fn(server, name, feedcode, amount, return_dict, order_N):
            return_dict[order_N] = server.sell(name, feedcode, 10, np.ceil(amount).astype(int))
        proc =  Process(target=fn, args = (self._server, self._name, feedcode, amount, self._proc_return_dict, self.order_N))
        print(self.order_N, "SELL", feedcode, amount)
        self._order_procs.append((self.order_N, proc));
        self.order_N += 1
        proc.start()



    def _process_orders(self):
        del_orders = []
        for i in range(len(self._order_procs)):
            order_N, proc = self._order_procs[i]
            if not proc.is_alive():
                proc.join()
                ret = self._proc_return_dict[order_N]
                del_orders.append(i)
                if ret is None:
                    print(order_N, "NOT ACK")
                elif int(ret['TRADED_VOLUME']) == 0:
                    print(order_N, "NO TRADE")
                else:
                    print(order_N, "ACK", ret['FEEDCODE'], ret['PRICE'], ret['TRADED_VOLUME'])

                    self.cash += -1*float(ret['PRICE'])*int(ret['TRADED_VOLUME'])
                    print( "CASH", self.cash)
                    if ret['FEEDCODE'] not in self._positions:
                        self._positions[ret['FEEDCODE']] = 0
                    self._positions[ret['FEEDCODE']] += int(ret['TRADED_VOLUME'])
        for i in del_orders[::-1]:
            del self._order_procs[i]

    def callback(self, entry):
        self._process_orders()
        self._callback(self, entry)


    def reset_positions(self):
        done = False
        while len(self._order_procs) != 0:
            time.sleep(1)
            self._process_orders()
        while not done:
            done = True
            for feedcode, value in self._positions.items():
                if value < 0:
                    self.buy(feedcode, min(-value,300))
                    done = False
                elif value>0:
                    self.sell(feedcode, min(value,300))
                    done = False
            while len(self._order_procs) != 0:
                time.sleep(1)
                self._process_orders()
        print("--------------- DONE RESETTING -------------")
        print( "CASH", self.cash)
        print("--------------------------------------------")
        self._server.clear_listen()




    def start_trading(self):
        self._server.register_callback(self.callback)
        self._server.start_listen(blocking=True)
Beispiel #13
0
async def add_interval(ctx,
                       subreddit: str = "r/funny",
                       time_span: str = "day",
                       interval_timeout: float = 1,
                       start_time: str = None):

    if not await is_admin(ctx):
        return None

    global f_updated
    global time_spans
    global running
    _guild_id = ctx.guild.id
    _channel = ctx.message.channel.id
    server = ServerInterface(mapi, _guild_id)

    # checking if intervals are available
    interval_id = server.add_id()

    if interval_id < 0:
        await ctx.send("No Intervals left")
        return None

    # sanitising subreddit and checking if it exists.
    if subreddit[:2] == "r/":
        subreddit = subreddit[2:]

    answer = requests.get(f"https://www.reddit.com/r/{subreddit}/about/.json",
                          headers={
                              'User-agent':
                              f'RedditTopOfDiscordBot '
                              f'{current_version:.1f}'
                          })
    if answer.status_code != 200:
        await ctx.send(f"The subreddit r/{subreddit} does not exist")
        return None

    if answer.json()['data']['over18'] and not server.nsfw:
        await ctx.send(
            f"Error. The subreddit r/{subreddit} is NSFW. Please enable NSFW content on your server, "
            f"with 'option NSFW true'")
        return None

    # sanitising time_span
    if time_span not in time_spans:
        await ctx.send(f"Not supported time_span, only {time_spans} supported")
        return None

    # interval_timeout
    if not debugging:
        if interval_timeout < 0.25:
            await ctx.send(
                f"Not supported interval_time, intervals smaller than 0.25h aren't allowed."
            )
            return None

    # sanitising start_time:
    if type(start_time) is str:
        try:
            # adding the current date to the time parameter
            cur_dt = datetime.datetime.utcnow()
            add_str = cur_dt.strftime("%Y.%m.%d")
            add_str += f"_{start_time}"

            # trying to load the new date
            start_dt = datetime.datetime.strptime(add_str, "%Y.%m.%d_%H:%M")

            # checking if the time_point has passed already.
            delta = start_dt - cur_dt

            # shifting
            if delta.total_seconds() <= 0:
                start_dt = start_dt + datetime.timedelta(days=1)
                await ctx.send(f"FYI: Scheduled post for tomorrow {start_time}"
                               )

        except ValueError as e:
            start_time = None
            print(e)
            await ctx.send("Error with given Start time. Assuming now")

        except Exception as e:
            await ctx.send(f"An unexpected error occured, contact the mods.")
            logging.exception(e)

    if start_time is None:
        start_dt = datetime.datetime.utcnow()

    start_dt = start_dt.replace(second=0, microsecond=0)

    qi.add_intervals(connection=mapi,
                     guild_id=_guild_id,
                     channel=_channel,
                     interval_id=interval_id,
                     subreddit=subreddit,
                     top_of=time_spans.index(time_span),
                     _time_shift=interval_timeout,
                     next_post_obj=start_dt)

    if not running:
        running = True
        bot.loop.create_task(queue_handler())

    if interval_id < 0:
        await ctx.send("No Intervals left")

    if interval_id >= 0:
        f_updated = True
        await ctx.send(f"Created interval with id {interval_id}")
Beispiel #14
0
async def fetch_post(
    guild_id,
    href:
    str = f"https://www.reddit.com/r/funny/top/.json?t=hour&limit={size_limit}"
):
    """
    Given a url, the function locates all the images by searching for post_hint == "image". For all found images, the
    function checks if the post is already in the list containing the already posted links. It then selects the first
    image that wasn't already posted and returns it.
    If all posts were already posted it deletes the stored posts and starts over.

    :param guild_id: Guild Id to send the fetched post to.

    :param href: complete href for a valid call to the reddit api for a json, example
        https://www.reddit.com/r/funny/top/.json?t=hour&limit=60

    :return: Either the href to a image or the http error code
    """
    global mapi
    response = ""
    img_urls = []
    server = ServerInterface(mapi, guild_id)

    nsfw = False
    try:
        nsfw = server.nsfw
    except ConnectionError as ex:
        logging.exception(ex)

    answer = requests.get(
        href,
        headers={'User-agent': f'RedditTopOfDiscordBot {current_version:.1f}'})
    poc(f"generated href: {href}")

    nsfw = server.nsfw

    if answer.status_code == 200:
        # parsing answer
        json_content = answer.json()

        for content in json_content["data"]["children"]:
            # Trying to check if post is a image, using post_hint
            # If no post_hint key is present, this post is skipped
            if "post_hint" in content["data"].keys():
                if content["data"]["post_hint"] != "image":
                    continue

            elif "is_gallery" in content["data"].keys():
                continue

            if "over_18" in content["data"].keys():
                if content["data"]["over_18"] and not nsfw:
                    continue

            img_urls.append(content["data"]["url"])

        # checking if image is posted already
        for href in img_urls:
            if server.add_post(href):
                response = href
                break

        # if all posts were already posted once
        if response == "":
            try:
                response = img_urls[0]
            except IndexError as ex:
                return f"Error: No Posts found"

        return response

    return f"Error: {answer.status_code}"