<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 <codeclass="xref py py-class docutils literal notranslate"><spanclass="pre">Command</span></code> 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>
<p>Now override the <codeclass="xref py py-meth docutils literal notranslate"><spanclass="pre">Command.run()</span></code> 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 <codeclass="xref py py-meth docutils literal notranslate"><spanclass="pre">CommandData.reply()</span></code> 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 <codeclass="xref py py-meth docutils literal notranslate"><spanclass="pre">Command.run()</span></code>
<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>
<p>If you don’t want arguments to be required, you can access them through the <codeclass="xref py py-meth docutils literal notranslate"><spanclass="pre">CommandArgs.optional()</span></code> 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>
<p>If you want the full argument string, you can use the <codeclass="xref py py-meth docutils literal notranslate"><spanclass="pre">CommandArgs.joined()</span></code> method.</p>
<p>You can specify a minimum number of arguments too, so that an <codeclass="xref py py-exc docutils literal notranslate"><spanclass="pre">InvalidInputError</span></code> 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 <codeclass="xref py py-meth docutils literal notranslate"><spanclass="pre">CommandArgs.match()</span></code> method, which tries to match a pattern to the command argument string,
which returns a tuple of the matched groups and raises an <codeclass="xref py py-exc docutils literal notranslate"><spanclass="pre">InvalidInputError</span></code> 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>
<p>If you want to display an error message to the user, you can raise a <codeclass="xref py py-exc docutils literal notranslate"><spanclass="pre">CommandError</span></code> 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>
<p>You can also manually raise <codeclass="xref py py-exc docutils literal notranslate"><spanclass="pre">InvalidInputError</span></code> 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
<codeclass="xref py py-exc docutils literal notranslate"><spanclass="pre">UnsupportedError</span></code> 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 <codeclass="xref py py-class docutils literal notranslate"><spanclass="pre">Command</span></code> 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 <codeclass="xref py py-meth docutils literal notranslate"><spanclass="pre">CommandData.reply()</span></code> 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 <codeclass="xref py py-func docutils literal notranslate"><spanclass="pre">royalnet.utils.asyncify()</span></code>
<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 <codeclass="xref py py-class docutils literal notranslate"><spanclass="pre">CommandData.delete_invoking</span></code>
<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
<p><codeclass="docutils literal notranslate"><spanclass="pre">self.interface.alchemy</span></code> is an instance of <codeclass="xref py py-class docutils literal notranslate"><spanclass="pre">royalnet.database.Alchemy</span></code>, 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 <codeclass="xref py py-class docutils literal notranslate"><spanclass="pre">royalnet.database.Alchemy</span></code> 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 <codeclass="xref py py-class docutils literal notranslate"><spanclass="pre">royalnet.database.Alchemy</span></code> with the same name they were created
<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 <codeclass="xref py py-func docutils literal notranslate"><spanclass="pre">royalnet.utils.asyncify()</span></code> 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.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>.