Passed
Push — master ( 5359ca...7c7d88 )
by Bob
04:42 queued 01:59
created

Dramiel.php (3 issues)

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
use Discord\Discord;
34
use Discord\Parts\Channel\Channel;
35
36
// More memory allowance
37
ini_set('memory_limit', '1024M');
38
39
// Just incase we get launched from somewhere else
40
chdir(__DIR__);
41
42
// Enable garbage collection
43
gc_enable();
44
45
// When the bot started
46
$startTime = time();
47
48
// create a log channel
49
$logger = new Logger('Dramiel');
50
$logger->pushHandler(new StreamHandler(__DIR__.'/log/dramielLog.log', Logger::DEBUG));
51
$logger->addInfo('Logger Initiated');
52
53
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...
54
55
// Require the config
56
if (file_exists('config/config.php')) {
57
    require_once 'config/config.php';
58
} else {
59
    $logger->error('config.php not found (you might wanna start by editing and renaming config_new.php)');
60
    die();
61
}
62
63
// Load the library files (Probably a prettier way to do this that i haven't thought up yet)
64
foreach (glob(__DIR__.'/src/lib/*.php') as $lib) {
65
    require_once $lib;
66
}
67
68
//Startup DB Check
69
updateDramielDB($logger);
70
updateCCPData($logger);
71
72
// Init Discord
73
use Discord\Parts\Channel\Message;
74
use Discord\Parts\User\Game;
75
use Discord\WebSockets\Event;
76
use Discord\WebSockets\WebSocket;
77
use Monolog\Handler\StreamHandler;
0 ignored issues
show
This code did not parse for me. Apparently, there is an error somewhere around this line:

Cannot use Monolog\Handler\StreamHandler as StreamHandler because the name is already in use
Loading history...
78
use Monolog\Logger;
79
80
$discord = new Discord(['token' => $config['bot']['token']]);
81
82
// Load tick plugins
83
$pluginDirs = ['src/plugins/onTick/*.php'];
84
$logger->info('Loading background plugins');
85
$plugins = [];
86
foreach ($pluginDirs as $dir) {
87
    foreach (glob($dir) as $plugin) {
88
        // Only load the plugins we want to load, according to the config
89
        if (!in_array(str_replace('.php', '', basename($plugin)), $config['enabledPlugins'])) {
90
            continue;
91
        }
92
93
        require_once $plugin;
94
        $fileName = str_replace('.php', '', basename($plugin));
95
        $p = new $fileName();
96
        $p->init($config, $discord, $logger);
97
        $pluginsT[] = $p;
98
    }
99
}
100
// Number of plugins loaded
101
$logger->info('Loaded: '.count($pluginsT).' background plugins');
102
103
// Load chat plugins
104
$pluginDirs = ['src/plugins/onMessage/*.php'];
105
$logger->addInfo('Loading in chat plugins');
106
$plugins = [];
107
foreach ($pluginDirs as $dir) {
108
    foreach (glob($dir) as $plugin) {
109
        // Only load the plugins we want to load, according to the config
110
        if (!in_array(str_replace('.php', '', basename($plugin)), $config['enabledPlugins'])) {
111
            continue;
112
        }
113
114
        require_once $plugin;
115
        $fileName = str_replace('.php', '', basename($plugin));
116
        $p = new $fileName();
117
        $p->init($config, $discord, $logger);
118
        $plugins[] = $p;
119
    }
120
}
121
122
// Number of chat plugins loaded
123
$logger->addInfo('Loaded: '.count($plugins).' chat plugins');
124
125
$ws = new WebSocket($discord);
126
127
$ws->on(
128
    'ready',
129
    function ($discord) use ($ws, $logger, $config, $plugins, $pluginsT) {
130
        // In here we can access any of the WebSocket events.
131
        //
132
        // There is a list of event constants that you can
133
        // find here: https://teamreflex.github.io/DiscordPHP/classes/Discord.WebSockets.Event.html
134
        //
135
        // We will echo to the console that the WebSocket is ready.
136
        $logger->addInfo('Discord WebSocket is ready!'.PHP_EOL);
137
        $game = new Game(['name' => $config['bot']['game'], 'url' => null, 'type' => null], true);
138
        $ws->updatePresence($game, false);
139
        // $ws->setNickname($config["bot"]["name"]); //not in yet
0 ignored issues
show
Unused Code Comprehensibility introduced by
80% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
140
141
        // Database check
142
        $ws->loop->addPeriodicTimer(86400, function () use ($logger) {
143
            updateDramielDB($logger);
144
            updateCCPData($logger);
145
        });
146
147
        // Run the Tick plugins
148
        $ws->loop->addPeriodicTimer(1, function () use ($pluginsT) {
149
            foreach ($pluginsT as $plugin) {
150
                $plugin->tick();
151
            }
152
        });
153
154
        // Mem cleanup every 30 minutes
155
        $ws->loop->addPeriodicTimer(1800, function () use ($logger) {
156
            $logger->addInfo('Memory in use: '.memory_get_usage() / 1024 / 1024 .'MB');
157
            gc_collect_cycles(); // Collect garbage
158
            $logger->addInfo('Memory in use after garbage collection: '.memory_get_usage() / 1024 / 1024 .'MB');
159
        });
160
161
        $ws->on(
162
            Event::MESSAGE_CREATE,
163
            function ($message, $discord, $newdiscord) use ($logger, $config, $plugins) {
164
                $msgData = [
165
                    'message' => [
166
                        'timestamp'         => $message->timestamp,
167
                        'id'                => $message->id,
168
                        'message'           => $message->content,
169
                        'channelID'         => $message->channel_id,
170
                        'from'              => $message->author->username,
171
                        'fromID'            => $message->author->id,
172
                        'fromDiscriminator' => $message->author->discriminator,
173
                        'fromAvatar'        => $message->author->avatar,
174
                    ],
175
                ];
176
177
                if ($message->content == '(╯°□°)╯︵ ┻━┻') {
178
                    $message->reply('┬─┬ ノ( ゜-゜ノ)');
179
                }
180
181
                // We are just checking if the message equals to ping and replying to the user with a pong!
182
                if ($message->content == 'ping') {
183
                    $message->reply('pong!');
184
                }
185
                // Check for plugins
186
                if (isset($message->content[0])) {
187
                    if ($message->content[0] == $config['bot']['trigger']) {
188
                        foreach ($plugins as $plugin) {
189
                            try {
190
                                $plugin->onMessage($msgData, $message);
191
                            } catch (Exception $e) {
192
                                $logger->addError('Error: '.$e->getMessage());
193
                            }
194
                        }
195
                    }
196
                }
197
            }
198
        );
199
    }
200
);
201
$ws->on(
202
    'error',
203
    function ($error, $ws) use ($logger) {
204
        $logger->addError($error);
205
        exit(1);
206
    }
207
);
208
$ws->on(
209
    'reconnecting',
210
    function () use ($logger) {
211
        $logger->addInfo('Websocket is reconnecting..');
212
    });
213
$ws->on(
214
    'reconnected',
215
    function () use ($logger) {
216
        $logger->addInfo('Websocket was reconnected..');
217
    });
218
// Now we will run the ReactPHP Event Loop!
219
$ws->run();
220