<liclass="toctree-l2"><aclass="reference internal"href="#running-code-at-the-initialization-of-the-bot">Running code at the initialization of the bot</a></li>
<h2>Creating a new Command<aclass="headerlink"href="#creating-a-new-command"title="Permalink to this headline">¶</a></h2>
<p>First, think of a <codeclass="docutils literal notranslate"><spanclass="pre">name</span></code> for your command.
It’s the name your command will be called with: for example, the “spaghetti” command will be called by typing <strong>/spaghetti</strong> in chat.
Try to keep the name as short as possible, while staying specific enough so no other command will have the same name.</p>
<p>Next, create a new Python file with the <codeclass="docutils literal notranslate"><spanclass="pre">name</span></code> you have thought of.
The previously mentioned “spaghetti” command should have a file called <codeclass="docutils literal notranslate"><spanclass="pre">spaghetti.py</span></code>.</p>
<p>Then, in the first row of the file, import the <aclass="reference internal"href="apireference.html#royalnet.commands.Command"title="royalnet.commands.Command"><codeclass="xref py py-class docutils literal notranslate"><spanclass="pre">Command</span></code></a> class from royalnet, and create a new class inheriting from it:</p>
<p>Inside the class, override the attributes <codeclass="docutils literal notranslate"><spanclass="pre">name</span></code> and <codeclass="docutils literal notranslate"><spanclass="pre">description</span></code> with respectively the <strong>name of the command</strong> and a <strong>small description of what the command will do</strong>:</p>
<spanclass="n">description</span><spanclass="o">=</span><spanclass="s2">"Send a spaghetti emoji in the chat."</span>
</pre></div>
</div>
<p>Now override the <aclass="reference internal"href="apireference.html#royalnet.commands.Command.run"title="royalnet.commands.Command.run"><codeclass="xref py py-meth docutils literal notranslate"><spanclass="pre">Command.run()</span></code></a> method, adding the code you want the bot to run when the command is called.</p>
<p>To send a message in the chat the command was called in, you can use the <aclass="reference internal"href="apireference.html#royalnet.commands.CommandData.reply"title="royalnet.commands.CommandData.reply"><codeclass="xref py py-meth docutils literal notranslate"><spanclass="pre">CommandData.reply()</span></code></a> method:</p>
<p>A command can have some arguments passed by the user: for example, on Telegram an user may type <cite>/spaghetti carbonara al-dente</cite>
to pass the <aclass="reference external"href="https://docs.python.org/3.7/library/stdtypes.html#str"title="(in Python v3.7)"><codeclass="xref py py-class docutils literal notranslate"><spanclass="pre">str</span></code></a><cite>“carbonara al-dente”</cite> to the command code.</p>
<p>These arguments can be accessed in multiple ways through the <codeclass="docutils literal notranslate"><spanclass="pre">args</span></code> parameter passed to the <aclass="reference internal"href="apireference.html#royalnet.commands.Command.run"title="royalnet.commands.Command.run"><codeclass="xref py py-meth docutils literal notranslate"><spanclass="pre">Command.run()</span></code></a>
<p>If you want your command to use arguments, override the <codeclass="docutils literal notranslate"><spanclass="pre">syntax</span></code> class attribute with a brief description of the
syntax of your command, possibly using (round parentheses) for required arguments and [square brackets] for optional
<spanclass="k">await</span><spanclass="n">data</span><spanclass="o">.</span><spanclass="n">reply</span><spanclass="p">(</span><spanclass="n">f</span><spanclass="s2">"🍝 Here's your </span><spanclass="si">{args[0]}</span><spanclass="s2">!"</span><spanclass="p">)</span>
<h3>Direct access<aclass="headerlink"href="#direct-access"title="Permalink to this headline">¶</a></h3>
<p>You can consider arguments as if they were separated by spaces.</p>
<p>You can then access command arguments directly by number as if the args object was a list of <aclass="reference external"href="https://docs.python.org/3.7/library/stdtypes.html#str"title="(in Python v3.7)"><codeclass="xref py py-class docutils literal notranslate"><spanclass="pre">str</span></code></a>.</p>
<p>If you request an argument with a certain number, but the argument does not exist, an
<codeclass="xref py py-exc docutils literal notranslate"><spanclass="pre">royalnet.error.InvalidInputError</span></code> is raised, making the arguments accessed in this way <strong>required</strong>.</p>
<spanclass="c1"># InvalidInputError() is raised</span>
</pre></div>
</div>
</div>
<divclass="section"id="optional-access">
<h3>Optional access<aclass="headerlink"href="#optional-access"title="Permalink to this headline">¶</a></h3>
<p>If you don’t want arguments to be required, you can access them through the <aclass="reference internal"href="apireference.html#royalnet.commands.CommandArgs.optional"title="royalnet.commands.CommandArgs.optional"><codeclass="xref py py-meth docutils literal notranslate"><spanclass="pre">CommandArgs.optional()</span></code></a> method: it
will return <codeclass="xref py py-const docutils literal notranslate"><spanclass="pre">None</span></code> if the argument wasn’t passed, making it <strong>optional</strong>.</p>
<p>You can specify a default result too, so that the method will return it instead of returning <codeclass="xref py py-const docutils literal notranslate"><spanclass="pre">None</span></code>:</p>
<h3>Full string<aclass="headerlink"href="#full-string"title="Permalink to this headline">¶</a></h3>
<p>If you want the full argument string, you can use the <aclass="reference internal"href="apireference.html#royalnet.commands.CommandArgs.joined"title="royalnet.commands.CommandArgs.joined"><codeclass="xref py py-meth docutils literal notranslate"><spanclass="pre">CommandArgs.joined()</span></code></a> method.</p>
<p>You can specify a minimum number of arguments too, so that an <aclass="reference internal"href="apireference.html#royalnet.commands.InvalidInputError"title="royalnet.commands.InvalidInputError"><codeclass="xref py py-exc docutils literal notranslate"><spanclass="pre">InvalidInputError</span></code></a> will be
<spanclass="c1"># InvalidInputError() is raised</span>
</pre></div>
</div>
</div>
<divclass="section"id="regular-expressions">
<h3>Regular expressions<aclass="headerlink"href="#regular-expressions"title="Permalink to this headline">¶</a></h3>
<p>For more complex commands, you may want to get arguments through <aclass="reference external"href="https://regexr.com/">regular expressions</a>.</p>
<p>You can then use the <aclass="reference internal"href="apireference.html#royalnet.commands.CommandArgs.match"title="royalnet.commands.CommandArgs.match"><codeclass="xref py py-meth docutils literal notranslate"><spanclass="pre">CommandArgs.match()</span></code></a> method, which tries to match a pattern to the command argument string,
which returns a tuple of the matched groups and raises an <aclass="reference internal"href="apireference.html#royalnet.commands.InvalidInputError"title="royalnet.commands.InvalidInputError"><codeclass="xref py py-exc docutils literal notranslate"><spanclass="pre">InvalidInputError</span></code></a> if there is no match.</p>
<p>To match a pattern, <aclass="reference external"href="https://docs.python.org/3.7/library/re.html#re.match"title="(in Python v3.7)"><codeclass="xref py py-func docutils literal notranslate"><spanclass="pre">re.match()</span></code></a> is used, meaning that Python will try to match only at the beginning of the string.</p>
<h2>Raising errors<aclass="headerlink"href="#raising-errors"title="Permalink to this headline">¶</a></h2>
<p>If you want to display an error message to the user, you can raise a <aclass="reference internal"href="apireference.html#royalnet.commands.CommandError"title="royalnet.commands.CommandError"><codeclass="xref py py-exc docutils literal notranslate"><spanclass="pre">CommandError</span></code></a> using the error message as argument:</p>
<spanclass="k">raise</span><spanclass="n">CommandError</span><spanclass="p">(</span><spanclass="s2">"The kitchen is closed. Come back later!"</span><spanclass="p">)</span>
</pre></div>
</div>
<p>You can also manually raise <aclass="reference internal"href="apireference.html#royalnet.commands.InvalidInputError"title="royalnet.commands.InvalidInputError"><codeclass="xref py py-exc docutils literal notranslate"><spanclass="pre">InvalidInputError</span></code></a> to redisplay the command syntax, along with your error message:</p>
<spanclass="k">raise</span><spanclass="n">InvalidInputError</span><spanclass="p">(</span><spanclass="s2">"The specified pasta type is invalid."</span><spanclass="p">)</span>
</pre></div>
</div>
<p>If you need a Royalnet feature that’s not available on the current interface, you can raise an
<aclass="reference internal"href="apireference.html#royalnet.commands.UnsupportedError"title="royalnet.commands.UnsupportedError"><codeclass="xref py py-exc docutils literal notranslate"><spanclass="pre">UnsupportedError</span></code></a> with a brief description of what’s missing:</p>
<spanclass="k">raise</span><spanclass="n">UnsupportedError</span><spanclass="p">(</span><spanclass="s2">"This command can only be run on Telegram interfaces."</span><spanclass="p">)</span>
<h2>Running code at the initialization of the bot<aclass="headerlink"href="#running-code-at-the-initialization-of-the-bot"title="Permalink to this headline">¶</a></h2>
<p>You can run code while the bot is starting by overriding the <codeclass="xref py py-meth docutils literal notranslate"><spanclass="pre">Command.__init__()</span></code> function.</p>
<p>You should keep the <codeclass="docutils literal notranslate"><spanclass="pre">super().__init__(interface)</span></code> call at the start of it, so that the <aclass="reference internal"href="apireference.html#royalnet.commands.Command"title="royalnet.commands.Command"><codeclass="xref py py-class docutils literal notranslate"><spanclass="pre">Command</span></code></a> instance is
initialized properly, then add your code after it.</p>
<p>You can add fields to the command to keep <strong>shared data between multiple command calls</strong> (but not bot restarts): it may
be useful for fetching external static data and keeping it until the bot is restarted, or to store references to all the
<aclass="reference external"href="https://docs.python.org/3.7/library/asyncio-task.html#asyncio.Task"title="(in Python v3.7)"><codeclass="xref py py-class docutils literal notranslate"><spanclass="pre">asyncio.Task</span></code></a> started by the bot.</p>
<spanclass="k">await</span><spanclass="n">data</span><spanclass="o">.</span><spanclass="n">reply</span><spanclass="p">(</span><spanclass="n">f</span><spanclass="s2">"⚠️ This pasta was already requested before."</span><spanclass="p">)</span>
<spanclass="k">await</span><spanclass="n">data</span><spanclass="o">.</span><spanclass="n">reply</span><spanclass="p">(</span><spanclass="n">f</span><spanclass="s2">"🍝 Here's your </span><spanclass="si">{pasta}</span><spanclass="s2">!"</span><spanclass="p">)</span>
<p>You may have noticed that in the previous examples we used <codeclass="docutils literal notranslate"><spanclass="pre">await</span><spanclass="pre">data.reply("🍝")</span></code> instead of just <codeclass="docutils literal notranslate"><spanclass="pre">data.reply("🍝")</span></code>.</p>
<p>This is because <aclass="reference internal"href="apireference.html#royalnet.commands.CommandData.reply"title="royalnet.commands.CommandData.reply"><codeclass="xref py py-meth docutils literal notranslate"><spanclass="pre">CommandData.reply()</span></code></a> isn’t a simple method: it is a coroutine, a special kind of function that
can be executed separately from the rest of the code, allowing the bot to do other things in the meantime.</p>
<p>By adding the <codeclass="docutils literal notranslate"><spanclass="pre">await</span></code> keyword before the <codeclass="docutils literal notranslate"><spanclass="pre">data.reply("🍝")</span></code>, we tell the bot that it can do other things, like
receiving new messages, while the message is being sent.</p>
<p>You should avoid running slow normal functions inside bot commands, as they will stop the bot from working until they
are finished and may cause bugs in other parts of the code!</p>
<p>If the slow function you want does not cause any side effect, you can wrap it with the <aclass="reference internal"href="apireference.html#royalnet.utils.asyncify"title="royalnet.utils.asyncify"><codeclass="xref py py-func docutils literal notranslate"><spanclass="pre">royalnet.utils.asyncify()</span></code></a>
<p>Avoid using <aclass="reference external"href="https://docs.python.org/3.7/library/time.html#time.sleep"title="(in Python v3.7)"><codeclass="xref py py-func docutils literal notranslate"><spanclass="pre">time.sleep()</span></code></a> function, as it is considered a slow operation: use instead <aclass="reference external"href="https://docs.python.org/3.7/library/asyncio-task.html#asyncio.sleep"title="(in Python v3.7)"><codeclass="xref py py-func docutils literal notranslate"><spanclass="pre">asyncio.sleep()</span></code></a>,
<h2>Delete the invoking message<aclass="headerlink"href="#delete-the-invoking-message"title="Permalink to this headline">¶</a></h2>
<p>The invoking message of a command is the message that the user sent that the bot recognized as a command; for example,
the message <codeclass="docutils literal notranslate"><spanclass="pre">/spaghetti</span><spanclass="pre">carbonara</span></code> is the invoking message for the <codeclass="docutils literal notranslate"><spanclass="pre">spaghetti</span></code> command run.</p>
<p>You can have the bot delete the invoking message for a command by calling the <aclass="reference internal"href="apireference.html#royalnet.commands.CommandData.delete_invoking"title="royalnet.commands.CommandData.delete_invoking"><codeclass="xref py py-class docutils literal notranslate"><spanclass="pre">CommandData.delete_invoking</span></code></a>
<p>Not all interfaces support deleting messages; by default, if the interface does not support deletions, the call is
ignored.</p>
<p>You can have the method raise an error if the message can’t be deleted by setting the <codeclass="docutils literal notranslate"><spanclass="pre">error_if_unavailable</span></code> parameter
<spanclass="k">await</span><spanclass="n">data</span><spanclass="o">.</span><spanclass="n">reply</span><spanclass="p">(</span><spanclass="s2">"🚫 The message could not be deleted."</span><spanclass="p">)</span>
<spanclass="k">else</span><spanclass="p">:</span>
<spanclass="k">await</span><spanclass="n">data</span><spanclass="o">.</span><spanclass="n">reply</span><spanclass="p">(</span><spanclass="s2">"✅ The message was deleted!"</span><spanclass="p">)</span>
<p>If the connection is established, the <codeclass="docutils literal notranslate"><spanclass="pre">self.interface.alchemy</span></code> and <codeclass="docutils literal notranslate"><spanclass="pre">self.interface.session</span></code> fields will be
available for use in commands.</p>
<p><codeclass="docutils literal notranslate"><spanclass="pre">self.interface.alchemy</span></code> is an instance of <aclass="reference internal"href="apireference.html#royalnet.database.Alchemy"title="royalnet.database.Alchemy"><codeclass="xref py py-class docutils literal notranslate"><spanclass="pre">royalnet.database.Alchemy</span></code></a>, which contains the
<aclass="reference external"href="https://docs.sqlalchemy.org/en/13/core/connections.html#sqlalchemy.engine.Engine"title="(in SQLAlchemy v1.3)"><codeclass="xref py py-class docutils literal notranslate"><spanclass="pre">sqlalchemy.engine.Engine</span></code></a>, metadata and tables, while <codeclass="docutils literal notranslate"><spanclass="pre">self.interface.session</span></code> is a
<aclass="reference external"href="https://docs.sqlalchemy.org/en/13/orm/session_api.html#sqlalchemy.orm.session.Session"title="(in SQLAlchemy v1.3)"><codeclass="xref py py-class docutils literal notranslate"><spanclass="pre">sqlalchemy.orm.session.Session</span></code></a>, and can be interacted in the same way as one.</p>
<p>If you want to use <aclass="reference internal"href="apireference.html#royalnet.database.Alchemy"title="royalnet.database.Alchemy"><codeclass="xref py py-class docutils literal notranslate"><spanclass="pre">royalnet.database.Alchemy</span></code></a> in your command, you should override the
<codeclass="docutils literal notranslate"><spanclass="pre">require_alchemy_tables</span></code> field with the <aclass="reference external"href="https://docs.python.org/3.7/library/stdtypes.html#set"title="(in Python v3.7)"><codeclass="xref py py-class docutils literal notranslate"><spanclass="pre">set</span></code></a> of Alchemy tables you need.</p>
<h3>Querying the database<aclass="headerlink"href="#querying-the-database"title="Permalink to this headline">¶</a></h3>
<p>You can <aclass="reference external"href="https://docs.sqlalchemy.org/en/13/orm/query.html#sqlalchemy.orm.query.Query"title="(in SQLAlchemy v1.3)"><codeclass="xref py py-class docutils literal notranslate"><spanclass="pre">sqlalchemy.orm.query.Query</span></code></a> the database using the SQLAlchemy ORM.</p>
<p>The SQLAlchemy tables can be found inside <aclass="reference internal"href="apireference.html#royalnet.database.Alchemy"title="royalnet.database.Alchemy"><codeclass="xref py py-class docutils literal notranslate"><spanclass="pre">royalnet.database.Alchemy</span></code></a> with the same name they were created
from, if they were specified in <codeclass="docutils literal notranslate"><spanclass="pre">require_alchemy_tables</span></code>.</p>
<h3>Adding filters to the query<aclass="headerlink"href="#adding-filters-to-the-query"title="Permalink to this headline">¶</a></h3>
<p>You can filter the query results with the <aclass="reference external"href="https://docs.sqlalchemy.org/en/13/orm/query.html#sqlalchemy.orm.query.Query.filter"title="(in SQLAlchemy v1.3)"><codeclass="xref py py-meth docutils literal notranslate"><spanclass="pre">sqlalchemy.orm.query.Query.filter()</span></code></a> method.</p>
<divclass="admonition note">
<pclass="admonition-title">Note</p>
<p>Remember to always use a table column as first comparision element, as it won’t work otherwise.</p>
<h3>Ordering the results of a query<aclass="headerlink"href="#ordering-the-results-of-a-query"title="Permalink to this headline">¶</a></h3>
<p>You can order the query results in <strong>ascending order</strong> with the <aclass="reference external"href="https://docs.sqlalchemy.org/en/13/orm/query.html#sqlalchemy.orm.query.Query.order_by"title="(in SQLAlchemy v1.3)"><codeclass="xref py py-meth docutils literal notranslate"><spanclass="pre">sqlalchemy.orm.query.Query.order_by()</span></code></a> method.</p>
<h3>Fetching the results of a query<aclass="headerlink"href="#fetching-the-results-of-a-query"title="Permalink to this headline">¶</a></h3>
<p>You can fetch the query results with the <aclass="reference external"href="https://docs.sqlalchemy.org/en/13/orm/query.html#sqlalchemy.orm.query.Query.all"title="(in SQLAlchemy v1.3)"><codeclass="xref py py-meth docutils literal notranslate"><spanclass="pre">sqlalchemy.orm.query.Query.all()</span></code></a>,
<p>Remember to use <aclass="reference internal"href="apireference.html#royalnet.utils.asyncify"title="royalnet.utils.asyncify"><codeclass="xref py py-func docutils literal notranslate"><spanclass="pre">royalnet.utils.asyncify()</span></code></a> when fetching results, as it may take a while!</p>
<p>Use <aclass="reference external"href="https://docs.sqlalchemy.org/en/13/orm/query.html#sqlalchemy.orm.query.Query.all"title="(in SQLAlchemy v1.3)"><codeclass="xref py py-meth docutils literal notranslate"><spanclass="pre">sqlalchemy.orm.query.Query.all()</span></code></a> if you want a <aclass="reference external"href="https://docs.python.org/3.7/library/stdtypes.html#list"title="(in Python v3.7)"><codeclass="xref py py-class docutils literal notranslate"><spanclass="pre">list</span></code></a> of <strong>all results</strong>:</p>
<p>Use <aclass="reference external"href="https://docs.sqlalchemy.org/en/13/orm/query.html#sqlalchemy.orm.query.Query.first"title="(in SQLAlchemy v1.3)"><codeclass="xref py py-meth docutils literal notranslate"><spanclass="pre">sqlalchemy.orm.query.Query.first()</span></code></a> if you want <strong>the first result</strong> of the list, or <codeclass="xref py py-const docutils literal notranslate"><spanclass="pre">None</span></code> if
<p>Use <aclass="reference external"href="https://docs.sqlalchemy.org/en/13/orm/query.html#sqlalchemy.orm.query.Query.one"title="(in SQLAlchemy v1.3)"><codeclass="xref py py-meth docutils literal notranslate"><spanclass="pre">sqlalchemy.orm.query.Query.one()</span></code></a> if you expect to have <strong>a single result</strong>, and you want the command to
raise an error if any different number of results is returned:</p>
<divclass="highlight-default notranslate"><divclass="highlight"><pre><span></span><spanclass="n">result</span><spanclass="p">:</span><spanclass="o">...</span><spanclass="o">=</span><spanclass="k">await</span><spanclass="n">asyncify</span><spanclass="p">(</span><spanclass="n">query</span><spanclass="o">.</span><spanclass="n">one</span><spanclass="p">)</span><spanclass="c1"># Raises an error if there are no results or more than a result.</span>
</pre></div>
</div>
<p>Use <aclass="reference external"href="https://docs.sqlalchemy.org/en/13/orm/query.html#sqlalchemy.orm.query.Query.one_or_none"title="(in SQLAlchemy v1.3)"><codeclass="xref py py-meth docutils literal notranslate"><spanclass="pre">sqlalchemy.orm.query.Query.one_or_none()</span></code></a> if you expect to have <strong>a single result</strong>, or <strong>nothing</strong>, and
if you want the command to raise an error if the number of results is greater than one.</p>
<divclass="highlight-default notranslate"><divclass="highlight"><pre><span></span><spanclass="n">result</span><spanclass="p">:</span><spanclass="n">typing</span><spanclass="o">.</span><spanclass="n">Union</span><spanclass="p">[</span><spanclass="o">...</span><spanclass="p">,</span><spanclass="kc">None</span><spanclass="p">]</span><spanclass="o">=</span><spanclass="k">await</span><spanclass="n">asyncify</span><spanclass="p">(</span><spanclass="n">query</span><spanclass="o">.</span><spanclass="n">one_or_none</span><spanclass="p">)</span><spanclass="c1"># Raises an error if there is more than a result.</span>
</pre></div>
</div>
</div>
<divclass="section"id="more-alchemy">
<h3>More Alchemy<aclass="headerlink"href="#more-alchemy"title="Permalink to this headline">¶</a></h3>
<p>You can read more about <codeclass="xref py py-mod docutils literal notranslate"><spanclass="pre">sqlalchemy</span></code> at their <aclass="reference external"href="https://www.sqlalchemy.org/">website</a>.</p>
Built with <ahref="http://sphinx-doc.org/">Sphinx</a> using a <ahref="https://github.com/rtfd/sphinx_rtd_theme">theme</a> provided by <ahref="https://readthedocs.org">Read the Docs</a>.