Debian Codegraph @

docpages/example_code/coro_simple_commands1.cpp

raw symbols SCIP
1 #include <dpp/dpp.h>
2
3 int main() {
4 dpp::cluster bot{"token"};
5
6 bot.on_log(dpp::utility::cout_logger());
7
8 bot.on_slashcommand([](const dpp::slashcommand_t& event) -> dpp::task<void> {
9 if (event.command.get_command_name() == "addemoji") {
10 dpp::cluster *cluster = event.owner;
11 // Retrieve parameter values
12 dpp::snowflake file_id = std::get<dpp::snowflake>(event.get_parameter("file"));
13 std::string emoji_name = std::get<std::string>(event.get_parameter("name"));
14
15 // Get the attachment from the resolved list
16 const dpp::attachment &attachment = event.command.get_resolved_attachment(file_id);
17
18 // For simplicity for this example we only support PNG
19 if (attachment.content_type != "image/png") {
20 // While we could use event.co_reply, we can just use event.reply, as we will exit the command anyway and don't need to wait on the result
21 event.reply("Error: type " + attachment.content_type + " not supported");
22 co_return;
23 }
24 // Send a "<bot> is thinking..." message, to wait on later so we can edit
25 dpp::async thinking = event.co_thinking(false);
26
27 // Download and co_await the result
28 dpp::http_request_completion_t response = co_await cluster->co_request(attachment.url, dpp::m_get);
29
30 if (response.status != 200) { // Page didn't send the image
31 co_await thinking; // Wait for the thinking response to arrive so we can edit
32 event.edit_response("Error: could not download the attachment");
33 } else {
34 // Load the image data in a dpp::emoji
35 dpp::emoji emoji(emoji_name);
36 emoji.load_image(response.body, dpp::image_type::i_png);
37
38 // Create the emoji and co_await the response
39 dpp::confirmation_callback_t confirmation = co_await cluster->co_guild_emoji_create(event.command.guild_id, emoji);
40
41 co_await thinking; // Wait for the thinking response to arrive so we can edit
42 if (confirmation.is_error()) {
43 event.edit_response("Error: could not add emoji: " + confirmation.get_error().message);
44 } else { // Success
45 event.edit_response("Successfully added " + confirmation.get<dpp::emoji>().get_mention()); // Show the new emoji
46 }
47 }
48 }
49 });
50
51 bot.on_ready([&bot](const dpp::ready_t& event) {
52 if (dpp::run_once<struct register_bot_commands>()) {
53 dpp::slashcommand command("addemoji", "Add an emoji", bot.me.id);
54 // Add file and name as required parameters
55 command.add_option(dpp::command_option(dpp::co_attachment, "file", "Select an image", true));
56 command.add_option(dpp::command_option(dpp::co_string, "name", "Name of the emoji to add", true));
57
58 bot.global_command_create(command);
59 }
60 });
61
62 bot.start(dpp::st_wait);
63
64 return 0;
65 }