Test Setup Failed
Push — master ( 1575e3...59e4ec )
by Bob
03:22
created

Dramiel.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
/**
3
 * The MIT License (MIT)
4
 *
5
 * Copyright (c) 2016  Robert Sardinia
6
 *
7
 * Permission is hereby granted, free of charge, to any person obtaining a copy
8
 * of this software and associated documentation files (the "Software"), to deal
9
 * in the Software without restriction, including without limitation the rights
10
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
 * copies of the Software, and to permit persons to whom the Software is
12
 * furnished to do so, subject to the following conditions:
13
 *
14
 * The above copyright notice and this permission notice shall be included in all
15
 * copies or substantial portions of the Software.
16
 *
17
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
 * SOFTWARE.
24
 */
25
26
// Require the vendor stuff
27
require_once(__DIR__ . "/vendor/autoload.php");
28
29
// Setup logger
30
use Monolog\Logger;
31
use Monolog\Handler\StreamHandler;
32
33
// More memory allowance
34
ini_set("memory_limit", "1024M");
35
36
// Just incase we get launched from somewhere else
37
chdir(__DIR__);
38
39
// Enable garbage collection
40
gc_enable();
41
42
// When the bot started
43
$startTime = time();
44
45
// create a log channel
46
$logger = new Logger('Dramiel');
47
$logger->pushHandler(new StreamHandler(__DIR__ . '/log/dramielLog.log', Logger::DEBUG));
48
$logger->addInfo('Logger Initiated');
49
50
GLOBAL $logger;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
51
52
// Require the config
53
if (file_exists("config/config.php")) {
54
    require_once("config/config.php");
55
} else {
56
    $logger->error("config.php not found (you might wanna start by editing and renaming config_new.php)");
57
    die();
58
}
59
60
// Load the library files (Probably a prettier way to do this that i haven't thought up yet)
61
foreach (glob(__DIR__ . "/src/lib/*.php") as $lib) {
62
    require_once($lib);
63
}
64
65
//Startup DB Check
66
updateDramielDB($logger);
67
updateCCPData($logger);
68
69
// Init Discord
70
use Discord\Discord;
71
use Discord\Parts\User\Game;
72
use Discord\WebSockets\Event;
73
use Discord\WebSockets\WebSocket;
74
75
$discord = new Discord(["token" => $config["bot"]["token"]]);
76
77
// Load tick plugins
78
$pluginDirs = array("src/plugins/onTick/*.php");
79
$logger->info("Loading background plugins");
80
$plugins = array();
81
foreach ($pluginDirs as $dir) {
82
    foreach (glob($dir) as $plugin) {
83
        // Only load the plugins we want to load, according to the config
84
        if (!in_array(str_replace(".php", "", basename($plugin)), $config["enabledPlugins"])) {
85
            continue;
86
        }
87
88
        require_once($plugin);
89
        $fileName = str_replace(".php", "", basename($plugin));
90
        $p = new $fileName();
91
        $p->init($config, $discord, $logger);
92
        $pluginsT[] = $p;
93
    }
94
}
95
// Number of plugins loaded
96
$logger->info("Loaded: " . count($pluginsT) . " background plugins");
97
98
if ($config["bot"]["silentMode"] == "false" || !isset($config["bot"]["silentMode"])) {
99
// Load chat plugins
100
    $pluginDirs = array("src/plugins/onMessage/*.php", "src/plugins/admin/*.php");
101
    $adminPlugins = array("setNickname", "updateBot", "holder");
102
    $logger->addInfo("Loading in chat plugins");
103
    $plugins = array();
104
    foreach ($pluginDirs as $dir) {
105
        foreach (glob($dir) as $plugin) {
106
            var_dump($plugin);
107
            var_dump($adminPlugins);
108
            // Only load the plugins we want to load, according to the config
109
            if (!in_array(str_replace(".php", "", basename($plugin)), $config["enabledPlugins"]) && !in_array(str_replace(".php", "", basename($plugin)), $adminPlugins)) {
110
                continue;
111
            }
112
113
            require_once($plugin);
114
            $fileName = str_replace(".php", "", basename($plugin));
115
            $p = new $fileName();
116
            $p->init($config, $discord, $logger);
117
            $plugins[] = $p;
118
        }
119
    }
120
121
// Number of chat plugins loaded
122
    $logger->addInfo("Loaded: " . count($plugins) . " chat plugins");
123
}
124
125
$discord->on(
126
    'ready',
127
    function($discord) use ($logger, $config, $plugins, $pluginsT) {
128
        // In here we can access any of the WebSocket events.
129
        //
130
        // There is a list of event constants that you can
131
        // find here: https://teamreflex.github.io/DiscordPHP/classes/Discord.WebSockets.Event.html
132
        //
133
        // We will echo to the console that the WebSocket is ready.
134
        $logger->addInfo('Discord WebSocket is ready!' . PHP_EOL);
135
136
        // Database check
137
        $discord->loop->addPeriodicTimer(86400, function() use ($logger) {
138
            updateDramielDB($logger);
139
            updateCCPData($logger);
140
        });
141
142
        // Run the Tick plugins
143
        $discord->loop->addPeriodicTimer(5, function() use ($pluginsT) {
144
            foreach ($pluginsT as $plugin)
145
                $plugin->tick();
146
        });
147
148
        // Mem cleanup every 30 minutes
149
        $discord->loop->addPeriodicTimer(1800, function() use ($logger) {
150
            $logger->addInfo("Memory in use: " . memory_get_usage() / 1024 / 1024 . "MB");
151
            gc_collect_cycles(); // Collect garbage
152
            $logger->addInfo("Memory in use after garbage collection: " . memory_get_usage() / 1024 / 1024 . "MB");
153
        });
154
155
        $discord->on(
156
            Event::MESSAGE_CREATE,
157
            function($message) use ($logger, $config, $plugins) {
158
159
                $msgData = array(
160
                    "message" => array(
161
                        "timestamp" => $message->timestamp,
162
                        "id" => $message->id,
163
                        "message" => $message->content,
164
                        "channelID" => $message->channel_id,
165
                        "from" => $message->author->username,
166
                        "fromID" => $message->author->id,
167
                        "fromDiscriminator" => $message->author->discriminator,
168
                        "fromAvatar" => $message->author->avatar
169
                    )
170
                );
171
172
                if ($message->content == '(╯°□°)╯︵ ┻━┻') {
173
                    $message->reply('┬─┬ ノ( ゜-゜ノ)');
174
                }
175
176
                // We are just checking if the message equals to ping and replying to the user with a pong!
177
                if ($message->content == 'ping') {
178
                    $message->reply('pong!');
179
                }
180
                // Check for plugins
181
                if (isset($message->content[0])) {
182
                    if ($message->content[0] == $config["bot"]["trigger"]) {
183
                        foreach ($plugins as $plugin) {
184
                            try {
185
                                $plugin->onMessage($msgData, $message);
186
                            } catch (Exception $e) {
187
                                $logger->addError("Error: " . $e->getMessage());
188
                            }
189
                        }
190
                    }
191
                }
192
            }
193
        );
194
    }
195
);
196
$discord->on(
197
    'error',
198
    function($error) use ($logger) {
199
        $logger->addError($error);
200
        exit(1);
201
    }
202
);
203
$discord->on(
204
    'reconnecting',
205
    function() use ($logger) {
206
        $logger->addInfo('Websocket is reconnecting..');
207
    });
208
$discord->on(
209
    'reconnected',
210
    function() use ($logger) {
211
        $logger->addInfo('Websocket was reconnected..');
212
    });
213
// Now we will run the ReactPHP Event Loop!
214
$discord->run();
215
216