Passed
Branch master (29155b)
by
unknown
03:29
created

Dramiel.php (5 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\User\Game;
32
use Discord\WebSockets\Event;
33
use Discord\WebSockets\WebSocket;
34
use Monolog\Handler\StreamHandler;
35
use Monolog\Logger;
36
37
// More memory allowance
38
ini_set("memory_limit", "1024M");
39
40
// Just incase we get launched from somewhere else
41
chdir(__DIR__);
42
43
// Enable garbage collection
44
gc_enable();
45
46
// When the bot started
47
$startTime = time();
48
49
// create a log channel
50
$logger = new Logger('Dramiel');
51
$logger->pushHandler(new StreamHandler(__DIR__ . '/log/dramielLog.log', Logger::DEBUG));
52
$logger->addInfo('Logger Initiated');
53
54
GLOBAL $logger;
55
56
// Require the config
57
if (file_exists("config/config.php")) {
58
    require_once("config/config.php");
59
} else {
60
    $logger->error("config.php not found (you might wanna start by editing and renaming config_new.php)");
61
    die();
62
}
63
64
// Load the library files (Probably a prettier way to do this that i haven't thought up yet)
65
foreach (glob(__DIR__ . "/src/lib/*.php") as $lib) {
66
    require_once($lib);
67
}
68
69
//Startup DB Check
70
updateDramielDB($logger);
71
72
// Init Discord
73
74
$discord = new Discord(["token" => $config["bot"]["token"]]);
75
76
// Load tick plugins
77
$pluginDirs = array("src/plugins/onTick/*.php");
78
$logger->info("Loading background plugins");
79
$plugins = array();
80
foreach ($pluginDirs as $dir) {
81
    foreach (glob($dir) as $plugin) {
82
        // Only load the plugins we want to load, according to the config
83
        if (!in_array(str_replace(".php", "", basename($plugin)), $config["enabledPlugins"])) {
84
            continue;
85
        }
86
87
        require_once($plugin);
88
        $fileName = str_replace(".php", "", basename($plugin));
89
        $p = new $fileName();
90
        $p->init($config, $discord, $logger);
91
        $pluginsT[] = $p;
92
    }
93
}
94
// Number of plugins loaded
95
$logger->info("Loaded: " . count($pluginsT) . " background plugins");
96
97
if ($config["bot"]["silentMode"] == "false" || !isset($config["bot"]["silentMode"])) {
98
// Load chat plugins
99
    $pluginDirs = array("src/plugins/onMessage/*.php", "src/plugins/admin/*.php");
100
    $adminPlugins = array("setNickname", "updateBot", "holder");
101
    $logger->addInfo("Loading in chat plugins");
102
    $plugins = array();
103
    foreach ($pluginDirs as $dir) {
104
        foreach (glob($dir) as $plugin) {
105
            // Only load the plugins we want to load, according to the config
106
            if (!in_array(str_replace(".php", "", basename($plugin)), $config["enabledPlugins"]) && !in_array(str_replace(".php", "", basename($plugin)), $adminPlugins)) {
107
                continue;
108
            }
109
110
            require_once($plugin);
111
            $fileName = str_replace(".php", "", basename($plugin));
112
            $p = new $fileName();
113
            $p->init($config, $discord, $logger);
114
            $plugins[] = $p;
115
        }
116
    }
117
118
// Number of chat plugins loaded
119
    $logger->addInfo("Loaded: " . count($plugins) . " chat plugins");
120
}
121
122
$discord->on(
123
    'ready',
124
    function ($discord) use ($logger, $config, $plugins, $pluginsT, $discord) {
125
        // In here we can access any of the WebSocket events.
126
        //
127
        // There is a list of event constants that you can
128
        // find here: https://teamreflex.github.io/DiscordPHP/classes/Discord.WebSockets.Event.html
129
        //
130
        // We will echo to the console that the WebSocket is ready.
131
        $logger->addInfo('Discord WebSocket is ready!' . PHP_EOL);
132
133
        // Database check
134
        $discord->loop->addPeriodicTimer(86400, function () use ($logger) {
135
            updateDramielDB($logger);
136
        });
137
138
        // Run the Tick plugins
139
        $discord->loop->addPeriodicTimer(3, function () use ($pluginsT) {
140
            foreach ($pluginsT as $plugin) {
141
                $plugin->tick();
142
            }
143
        });
144
145
        // Message queue
146
        $discord->loop->addPeriodicTimer(15, function () use ($discord,$logger) {
147
            $id = getPermCache("messageQueueID");
148
            if(is_null($id)){
149
                $id = 1;
150
            }
151
            $queuedMessage = getQueuedMessage($id);
152 View Code Duplication
            if(!is_null($queuedMessage)){
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...
153
                $guild = $discord->guilds->get('id', $queuedMessage['guild']);
154
                $channel = $guild->channels->get('id', $queuedMessage['channel']);
155
                $logger->addInfo("QueueProcessing - Completing queued item #{$id} : {$queuedMessage['message']}");
156
                $channel->sendMessage($queuedMessage['message'], false);
157
                $id = $id + 1;
158
                setPermCache("messageQueueID", $id);
159
                //clearQueuedMessages($id); bugtest me
160
            }
161
            $queuedMessage = getQueuedMessage($id);
0 ignored issues
show
Are you sure the assignment to $queuedMessage is correct as getQueuedMessage($id) (which targets getQueuedMessage()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
162 View Code Duplication
            if(!is_null($queuedMessage)){
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...
163
                $guild = $discord->guilds->get('id', $queuedMessage['guild']);
0 ignored issues
show
The property guilds does not seem to exist. Did you mean largeGuilds?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
164
                $channel = $guild->channels->get('id', $queuedMessage['channel']);
165
                $logger->addInfo("QueueProcessing - Completing queued item #{$id} : {$queuedMessage['message']}");
166
                $channel->sendMessage($queuedMessage['message'], false);
167
                $id = $id + 1;
168
                setPermCache("messageQueueID", $id);
169
                //clearQueuedMessages($id); bugtest me
0 ignored issues
show
Unused Code Comprehensibility introduced by
45% 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...
170
            }
171
        });
172
173
        // Mem cleanup every 30 minutes
174
        $discord->loop->addPeriodicTimer(1800, function () use ($logger) {
175
            $logger->addInfo("Memory in use: " . memory_get_usage() / 1024 / 1024 . "MB");
176
            gc_collect_cycles(); // Collect garbage
177
            $logger->addInfo("Memory in use after garbage collection: " . memory_get_usage() / 1024 / 1024 . "MB");
178
        });
179
180
        $discord->on(
181
            Event::MESSAGE_CREATE,
182
            function ($message) use ($logger, $config, $plugins) {
183
184
                $msgData = array(
185
                    "message" => array(
186
                        "timestamp" => $message->timestamp,
187
                        "id" => $message->id,
188
                        "message" => $message->content,
189
                        "channelID" => $message->channel_id,
190
                        "from" => $message->author->username,
191
                        "fromID" => $message->author->id,
192
                        "fromDiscriminator" => $message->author->discriminator,
193
                        "fromAvatar" => $message->author->avatar
194
                    )
195
                );
196
197
                if ($message->content == '(╯°□°)╯︵ ┻━┻') {
198
                    $message->reply('┬─┬ ノ( ゜-゜ノ)');
199
                }
200
201
                // We are just checking if the message equals to ping and replying to the user with a pong!
202
                if ($message->content == 'ping') {
203
                    $message->reply('pong!');
204
                }
205
                // Check for plugins
206
                if (isset($message->content[0])) {
207
                    if ($message->content[0] == $config["bot"]["trigger"]) {
208
                        foreach ($plugins as $plugin) {
209
                            try {
210
                                $plugin->onMessage($msgData, $message);
211
                            } catch (Exception $e) {
212
                                $logger->addError("Error: " . $e->getMessage());
213
                            }
214
                        }
215
                    }
216
                }
217
            }
218
        );
219
    }
220
);
221
$discord->on(
222
    'error',
223
    function ($error) use ($logger) {
224
        $logger->addError($error);
225
        exit(1);
226
    }
227
);
228
$discord->on(
229
    'reconnecting',
230
    function () use ($logger) {
231
        $logger->addInfo('Websocket is reconnecting..');
232
    });
233
$discord->on(
234
    'reconnected',
235
    function () use ($logger) {
236
        $logger->addInfo('Websocket was reconnected..');
237
    });
238
// Now we will run the ReactPHP Event Loop!
239
$discord->run();
240
241