Passed
Pull Request — master (#8)
by Bob
03:01
created

Dramiel.php (11 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 Discord\Discord;
31
use Discord\Parts\Channel\Channel;
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\Parts\Channel\Message;
71
use Discord\Parts\User\Game;
72
use Discord\WebSockets\Event;
73
use Discord\WebSockets\WebSocket;
74
use Monolog\Handler\StreamHandler;
75
use Monolog\Logger;
76
77
$discord = new Discord(['token' => $config['bot']['token']]);
78
79
// Load tick plugins
80
$pluginDirs = ['src/plugins/onTick/*.php'];
81
$logger->info('Loading background plugins');
82
$plugins = [];
83 View Code Duplication
foreach ($pluginDirs as $dir) {
0 ignored issues
show
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
84
    foreach (glob($dir) as $plugin) {
85
        // Only load the plugins we want to load, according to the config
86
        if (!in_array(str_replace('.php', '', basename($plugin)), $config['enabledPlugins'])) {
87
            continue;
88
        }
89
90
        require_once $plugin;
91
        $fileName = str_replace('.php', '', basename($plugin));
92
        $p = new $fileName();
93
        $p->init($config, $discord, $logger);
94
        $pluginsT[] = $p;
95
    }
96
}
97
// Number of plugins loaded
98
$logger->info('Loaded: '.count($pluginsT).' background plugins');
99
100
// Load chat plugins
101
$pluginDirs = ['src/plugins/onMessage/*.php'];
102
$logger->addInfo('Loading in chat plugins');
103
$plugins = [];
104 View Code Duplication
foreach ($pluginDirs as $dir) {
0 ignored issues
show
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
105
    foreach (glob($dir) as $plugin) {
106
        // Only load the plugins we want to load, according to the config
107
        if (!in_array(str_replace('.php', '', basename($plugin)), $config['enabledPlugins'])) {
108
            continue;
109
        }
110
111
        require_once $plugin;
112
        $fileName = str_replace('.php', '', basename($plugin));
113
        $p = new $fileName();
114
        $p->init($config, $discord, $logger);
115
        $plugins[] = $p;
116
    }
117
}
118
119
// Number of chat plugins loaded
120
$logger->addInfo('Loaded: '.count($plugins).' chat plugins');
121
122
$ws = new WebSocket($discord);
123
124
$ws->on(
125
    'ready',
126
    function ($discord) use ($ws, $logger, $config, $plugins, $pluginsT) {
0 ignored issues
show
The parameter $discord is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
127
        // In here we can access any of the WebSocket events.
128
        //
129
        // There is a list of event constants that you can
130
        // find here: https://teamreflex.github.io/DiscordPHP/classes/Discord.WebSockets.Event.html
131
        //
132
        // We will echo to the console that the WebSocket is ready.
133
        $logger->addInfo('Discord WebSocket is ready!'.PHP_EOL);
134
        $game = new Game(['name' => $config['bot']['game'], 'url' => null, 'type' => null], true);
135
        $ws->updatePresence($game, false);
136
        // $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...
137
138
        // Database check
139
        $ws->loop->addPeriodicTimer(86400, function () use ($logger) {
1 ignored issue
show
The method addPeriodicTimer() does not seem to exist on object<React\EventLoop\Factory>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
140
            updateDramielDB($logger);
141
            updateCCPData($logger);
142
        });
143
144
        // Run the Tick plugins
145
        $ws->loop->addPeriodicTimer(1, function () use ($pluginsT) {
1 ignored issue
show
The method addPeriodicTimer() does not seem to exist on object<React\EventLoop\Factory>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
146
            foreach ($pluginsT as $plugin) {
147
                $plugin->tick();
148
            }
149
        });
150
151
        // Mem cleanup every 30 minutes
152
        $ws->loop->addPeriodicTimer(1800, function () use ($logger) {
1 ignored issue
show
The method addPeriodicTimer() does not seem to exist on object<React\EventLoop\Factory>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
153
            $logger->addInfo('Memory in use: '.memory_get_usage() / 1024 / 1024 .'MB');
154
            gc_collect_cycles(); // Collect garbage
155
            $logger->addInfo('Memory in use after garbage collection: '.memory_get_usage() / 1024 / 1024 .'MB');
156
        });
157
158
        $ws->on(
159
            Event::MESSAGE_CREATE,
160
            function ($message, $discord, $newdiscord) use ($logger, $config, $plugins) {
0 ignored issues
show
The parameter $discord is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
The parameter $newdiscord is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
161
                $msgData = [
162
                    'message' => [
163
                        'timestamp'         => $message->timestamp,
164
                        'id'                => $message->id,
165
                        'message'           => $message->content,
166
                        'channelID'         => $message->channel_id,
167
                        'from'              => $message->author->username,
168
                        'fromID'            => $message->author->id,
169
                        'fromDiscriminator' => $message->author->discriminator,
170
                        'fromAvatar'        => $message->author->avatar,
171
                    ],
172
                ];
173
174
                if ($message->content == '(╯°□°)╯︵ ┻━┻') {
175
                    $message->reply('┬─┬ ノ( ゜-゜ノ)');
176
                }
177
178
                // We are just checking if the message equals to ping and replying to the user with a pong!
179
                if ($message->content == 'ping') {
180
                    $message->reply('pong!');
181
                }
182
                // Check for plugins
183
                if (isset($message->content[0])) {
184
                    if ($message->content[0] == $config['bot']['trigger']) {
185
                        foreach ($plugins as $plugin) {
186
                            try {
187
                                $plugin->onMessage($msgData, $message);
188
                            } catch (Exception $e) {
189
                                $logger->addError('Error: '.$e->getMessage());
190
                            }
191
                        }
192
                    }
193
                }
194
            }
195
        );
196
    }
197
);
198
$ws->on(
199
    'error',
200
    function ($error, $ws) use ($logger) {
0 ignored issues
show
The parameter $ws is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
201
        $logger->addError($error);
202
        exit(1);
203
    }
204
);
205
$ws->on(
206
    'reconnecting',
207
    function () use ($logger) {
208
        $logger->addInfo('Websocket is reconnecting..');
209
    });
210
$ws->on(
211
    'reconnected',
212
    function () use ($logger) {
213
        $logger->addInfo('Websocket was reconnected..');
214
    });
215
// Now we will run the ReactPHP Event Loop!
216
$ws->run();
217