Passed
Push — master ( fd77ed...f01db1 )
by Bob
03:00
created

Dramiel.php (1 issue)

Labels
Severity

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
<<<<<<< HEAD
0 ignored issues
show
This code did not parse for me. Apparently, there is an error somewhere around this line:

Syntax error, unexpected T_SL
Loading history...
33
34
use Discord\Discord;
35
use Discord\Parts\Channel\Channel;
36
=======
37
>>>>>>> parent of fb6ce12... Merge pull request #8 from shibdib/analysis-Xa6ARV
38
39
// More memory allowance
40
ini_set("memory_limit", "1024M");
41
42
// Just incase we get launched from somewhere else
43
chdir(__DIR__);
44
45
// Enable garbage collection
46
gc_enable();
47
48
// When the bot started
49
$startTime = time();
50
51
// create a log channel
52
$logger = new Logger('Dramiel');
53
$logger->pushHandler(new StreamHandler(__DIR__ . '/log/dramielLog.log', Logger::DEBUG));
54
$logger->addInfo('Logger Initiated');
55
56
GLOBAL $logger;
57
58
// Require the config
59
if (file_exists("config/config.php")) {
60
    require_once("config/config.php");
61
} else {
62
    $logger->error("config.php not found (you might wanna start by editing and renaming config_new.php)");
63
    die();
64
}
65
66
// Load the library files (Probably a prettier way to do this that i haven't thought up yet)
67
foreach (glob(__DIR__ . "/src/lib/*.php") as $lib) {
68
    require_once($lib);
69
}
70
71
//Startup DB Check
72
updateDramielDB($logger);
73
updateCCPData($logger);
74
75
// Init Discord
76
use Discord\Cache\Cache;
77
use Discord\Cache\Drivers\ArrayCacheDriver;
78
use Discord\Discord;
79
use Discord\Parts\Channel\Message;
80
use Discord\Parts\Channel\Channel;
81
use Discord\Parts\Guild\Guild;
82
use Discord\Parts\User\Game;
83
use Discord\Parts\User\Member;
84
use Discord\Parts\WebSockets\PresenceUpdate;
85
use Discord\WebSockets\Event;
86
use Discord\WebSockets\WebSocket;
87
88
$discord = new Discord(["token" => $config["bot"]["token"]]);
89
90
// Load tick plugins
91
$pluginDirs = array("src/plugins/onTick/*.php");
92
$logger->info("Loading background plugins");
93
$plugins = array();
94
foreach ($pluginDirs as $dir) {
95
    foreach (glob($dir) as $plugin) {
96
        // Only load the plugins we want to load, according to the config
97
        if (!in_array(str_replace(".php", "", basename($plugin)), $config["enabledPlugins"])) {
98
            continue;
99
        }
100
101
        require_once($plugin);
102
        $fileName = str_replace(".php", "", basename($plugin));
103
        $p = new $fileName();
104
        $p->init($config, $discord, $logger);
105
        $pluginsT[] = $p;
106
    }
107
}
108
// Number of plugins loaded
109
$logger->info("Loaded: " . count($pluginsT) . " background plugins");
110
111
// Load chat plugins
112
$pluginDirs = array("src/plugins/onMessage/*.php");
113
$logger->addInfo("Loading in chat plugins");
114
$plugins = array();
115
foreach ($pluginDirs as $dir) {
116
    foreach (glob($dir) as $plugin) {
117
        // Only load the plugins we want to load, according to the config
118
        if (!in_array(str_replace(".php", "", basename($plugin)), $config["enabledPlugins"])) {
119
            continue;
120
        }
121
122
        require_once($plugin);
123
        $fileName = str_replace(".php", "", basename($plugin));
124
        $p = new $fileName();
125
        $p->init($config, $discord, $logger);
126
        $plugins[] = $p;
127
    }
128
}
129
130
// Number of chat plugins loaded
131
$logger->addInfo("Loaded: " . count($plugins) . " chat plugins");
132
133
$ws = new WebSocket($discord);
134
135
$ws->on(
136
    'ready',
137
    function($discord) use ($ws, $logger, $config, $plugins, $pluginsT) {
138
        // In here we can access any of the WebSocket events.
139
        //
140
        // There is a list of event constants that you can
141
        // find here: https://teamreflex.github.io/DiscordPHP/classes/Discord.WebSockets.Event.html
142
        //
143
        // We will echo to the console that the WebSocket is ready.
144
        $logger->addInfo('Discord WebSocket is ready!' . PHP_EOL);
145
        $game = new Game(array('name' => $config["bot"]["game"], 'url' => null, 'type' => null), true);
146
        $ws->updatePresence($game, false);
147
        // $ws->setNickname($config["bot"]["name"]); //not in yet
148
149
        // Database check
150
        $ws->loop->addPeriodicTimer(86400, function() use ($logger) {
151
            updateDramielDB($logger); 
152
            updateCCPData($logger);
153
        });
154
        
155
        // Run the Tick plugins
156
        $ws->loop->addPeriodicTimer(1, function() use ($pluginsT) {
157
            foreach ($pluginsT as $plugin)
158
                $plugin->tick();
159
        });
160
161
        // Mem cleanup every 30 minutes
162
        $ws->loop->addPeriodicTimer(1800, function() use ($logger) {
163
            $logger->addInfo("Memory in use: " . memory_get_usage() / 1024 / 1024 . "MB");
164
            gc_collect_cycles(); // Collect garbage
165
            $logger->addInfo("Memory in use after garbage collection: " . memory_get_usage() / 1024 / 1024 . "MB");
166
        });
167
168
        $ws->on(
169
            Event::MESSAGE_CREATE,
170
            function($message, $discord, $newdiscord) use ($logger, $config, $plugins) {
171
172
                $msgData = array(
173
                    "message" => array(
174
                        "timestamp" => $message->timestamp,
175
                        "id" => $message->id,
176
                        "message" => $message->content,
177
                        "channelID" => $message->channel_id,
178
                        "from" => $message->author->username,
179
                        "fromID" => $message->author->id,
180
                        "fromDiscriminator" => $message->author->discriminator,
181
                        "fromAvatar" => $message->author->avatar
182
                    )
183
                );
184
185
                if ($message->content == '(╯°□°)╯︵ ┻━┻') {
186
                    $message->reply('┬─┬ ノ( ゜-゜ノ)');
187
                }
188
189
                // We are just checking if the message equals to ping and replying to the user with a pong!
190
                if ($message->content == 'ping') {
191
                    $message->reply('pong!');
192
                }
193
                // Check for plugins
194
                if (isset($message->content[0])) {
195
                    if ($message->content[0] == $config["bot"]["trigger"]) {
196
                        foreach ($plugins as $plugin) {
197
                            try {
198
                                $plugin->onMessage($msgData, $message);
199
                            } catch (Exception $e) {
200
                                $logger->addError("Error: " . $e->getMessage());
201
                            }
202
                        }
203
                    }
204
                }
205
            }
206
        );
207
    }
208
);
209
$ws->on(
210
    'error',
211
    function($error, $ws) use ($logger) {
212
        $logger->addError($error);
213
        exit(1);
214
    }
215
);
216
$ws->on(
217
    'reconnecting',
218
    function() use ($logger) {
219
        $logger->addInfo('Websocket is reconnecting..');
220
});
221
$ws->on(
222
    'reconnected',
223
    function() use ($logger) {
224
        $logger->addInfo('Websocket was reconnected..');
225
});
226
// Now we will run the ReactPHP Event Loop!
227
$ws->run();
228
229