Passed
Push — master ( 7c7d88...5359ca )
by Bob
03:13 queued 30s
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 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\Cache\Cache;
71
use Discord\Cache\Drivers\ArrayCacheDriver;
72
use Discord\Discord;
73
use Discord\Parts\Channel\Message;
74
use Discord\Parts\Channel\Channel;
75
use Discord\Parts\Guild\Guild;
76
use Discord\Parts\User\Game;
77
use Discord\Parts\User\Member;
78
use Discord\Parts\WebSockets\PresenceUpdate;
79
use Discord\WebSockets\Event;
80
use Discord\WebSockets\WebSocket;
81
82
$discord = new Discord(["token" => $config["bot"]["token"]]);
83
84
// Load tick plugins
85
$pluginDirs = array("src/plugins/onTick/*.php");
86
$logger->info("Loading background plugins");
87
$plugins = array();
88 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...
89
    foreach (glob($dir) as $plugin) {
90
        // Only load the plugins we want to load, according to the config
91
        if (!in_array(str_replace(".php", "", basename($plugin)), $config["enabledPlugins"])) {
92
            continue;
93
        }
94
95
        require_once($plugin);
96
        $fileName = str_replace(".php", "", basename($plugin));
97
        $p = new $fileName();
98
        $p->init($config, $discord, $logger);
99
        $pluginsT[] = $p;
100
    }
101
}
102
// Number of plugins loaded
103
$logger->info("Loaded: " . count($pluginsT) . " background plugins");
104
105
// Load chat plugins
106
$pluginDirs = array("src/plugins/onMessage/*.php");
107
$logger->addInfo("Loading in chat plugins");
108
$plugins = array();
109 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...
110
    foreach (glob($dir) as $plugin) {
111
        // Only load the plugins we want to load, according to the config
112
        if (!in_array(str_replace(".php", "", basename($plugin)), $config["enabledPlugins"])) {
113
            continue;
114
        }
115
116
        require_once($plugin);
117
        $fileName = str_replace(".php", "", basename($plugin));
118
        $p = new $fileName();
119
        $p->init($config, $discord, $logger);
120
        $plugins[] = $p;
121
    }
122
}
123
124
// Number of chat plugins loaded
125
$logger->addInfo("Loaded: " . count($plugins) . " chat plugins");
126
127
$ws = new WebSocket($discord);
128
129
$ws->on(
130
    'ready',
131
    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...
132
        // In here we can access any of the WebSocket events.
133
        //
134
        // There is a list of event constants that you can
135
        // find here: https://teamreflex.github.io/DiscordPHP/classes/Discord.WebSockets.Event.html
136
        //
137
        // We will echo to the console that the WebSocket is ready.
138
        $logger->addInfo('Discord WebSocket is ready!' . PHP_EOL);
139
        $game = new Game(array('name' => $config["bot"]["game"], 'url' => null, 'type' => null), true);
140
        $ws->updatePresence($game, false);
141
        // $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...
142
143
        // Database check
144
        $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...
145
            updateDramielDB($logger); 
146
            updateCCPData($logger);
147
        });
148
        
149
        // Run the Tick plugins
150
        $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...
151
            foreach ($pluginsT as $plugin)
152
                $plugin->tick();
153
        });
154
155
        // Mem cleanup every 30 minutes
156
        $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...
157
            $logger->addInfo("Memory in use: " . memory_get_usage() / 1024 / 1024 . "MB");
158
            gc_collect_cycles(); // Collect garbage
159
            $logger->addInfo("Memory in use after garbage collection: " . memory_get_usage() / 1024 / 1024 . "MB");
160
        });
161
162
        $ws->on(
163
            Event::MESSAGE_CREATE,
164
            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...
165
166
                $msgData = array(
167
                    "message" => array(
168
                        "timestamp" => $message->timestamp,
169
                        "id" => $message->id,
170
                        "message" => $message->content,
171
                        "channelID" => $message->channel_id,
172
                        "from" => $message->author->username,
173
                        "fromID" => $message->author->id,
174
                        "fromDiscriminator" => $message->author->discriminator,
175
                        "fromAvatar" => $message->author->avatar
176
                    )
177
                );
178
179
                if ($message->content == '(╯°□°)╯︵ ┻━┻') {
180
                    $message->reply('┬─┬ ノ( ゜-゜ノ)');
181
                }
182
183
                // We are just checking if the message equals to ping and replying to the user with a pong!
184
                if ($message->content == 'ping') {
185
                    $message->reply('pong!');
186
                }
187
                // Check for plugins
188
                if (isset($message->content[0])) {
189
                    if ($message->content[0] == $config["bot"]["trigger"]) {
190
                        foreach ($plugins as $plugin) {
191
                            try {
192
                                $plugin->onMessage($msgData, $message);
193
                            } catch (Exception $e) {
194
                                $logger->addError("Error: " . $e->getMessage());
195
                            }
196
                        }
197
                    }
198
                }
199
            }
200
        );
201
    }
202
);
203
$ws->on(
204
    'error',
205
    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...
206
        $logger->addError($error);
207
        exit(1);
208
    }
209
);
210
$ws->on(
211
    'reconnecting',
212
    function() use ($logger) {
213
        $logger->addInfo('Websocket is reconnecting..');
214
});
215
$ws->on(
216
    'reconnected',
217
    function() use ($logger) {
218
        $logger->addInfo('Websocket was reconnected..');
219
});
220
// Now we will run the ReactPHP Event Loop!
221
$ws->run();
222
223