<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Rafael Salimov on Medium]]></title>
        <description><![CDATA[Stories by Rafael Salimov on Medium]]></description>
        <link>https://medium.com/@rafasalimov?source=rss-750455dcf7c0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*LOfbc7zi3AApUGNxkd3L6Q.png</url>
            <title>Stories by Rafael Salimov on Medium</title>
            <link>https://medium.com/@rafasalimov?source=rss-750455dcf7c0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 14:25:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rafasalimov/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Writing Custom Management Commands in Django]]></title>
            <link>https://medium.com/analytics-vidhya/writing-custom-management-commands-in-django-d66044c37433?source=rss-750455dcf7c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/d66044c37433</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Rafael Salimov]]></dc:creator>
            <pubDate>Sun, 07 Mar 2021 15:34:43 GMT</pubDate>
            <atom:updated>2021-03-07T15:34:43.036Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*4bWZeYUVLSN-S54N.jpeg" /><figcaption>Image source: <a href="https://miro.medium.com/max/1838/1*_jaOKxXn1e7ho6mhT4U7Ow.jpeg">here</a></figcaption></figure><p>Sometimes we need to execute one-off tasks. For example: change something from the database automatically, send reports or notifications, schedule some tasks, and so on. If you want to call these commands whenever you want then management commands are the best choice. You can even use management commands as <strong>workers</strong> in production. Django itself has several commands such as <strong><em>migrate, makemigrations, runserver</em></strong>, and so on. Now I will show you have to write your own management command. Let’s begin!</p><h3>Project Structure</h3><p>I assume you already have a ready Django project called <strong>“my_project”</strong> and an app called <strong>“my_app”</strong>. Go inside this app, and create parent directory <strong>“management”</strong> and child directory <strong>commands.</strong> Now your project structure should look like that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*4RVlhzLdZ0G1F8miPIK4TA.png" /><figcaption>Ignore <strong>__pycache__</strong> directory</figcaption></figure><h3><strong>Command</strong></h3><p>Create a python file with the name <strong>“my_command.py”</strong> inside the commands directory:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*kDxCllVz1aiXGGZj_DCY6A.png" /></figure><p>Let’s open <strong>my_command.py </strong>and create simple command to check whether the command works or not. To write a command we have to define a <strong>Command </strong>class that inherits from <strong>BaseCommand </strong>class. To do that let’s import <strong>BaseCommand </strong>and <strong>CommandError </strong>classes to handle errors, too.</p><pre>from django.core.management.base import BaseCommand, CommandError</pre><pre>class Command(BaseCommand):<br>    help = &quot;Command to print a text&quot;</pre><pre>def handle(self, *args, **options):<br>        try:<br>            print(&#39;Command is executed&#39;)<br>        except Exception as e:<br>            raise CommandError(e)</pre><p>You can define a variable <strong>help</strong> to explain what is the purpose of the command. The function <strong>handle </strong>will execute our command. The command is done, let’s check it. Open the terminal and call it with the following command:</p><pre>py manage.py my_command</pre><p>You will see the output: <strong><em>Command is executed</em></strong></p><p>We learned how to write a simple command, and now we can execute more advanced commands such as sending reports, emails, and so on. Let’s do it:</p><h4>1. Create a Report model:</h4><p>Go to <strong>my_app.models</strong> and create a model:</p><pre><em>from</em> django.db <em>import</em> models</pre><pre>class Report(models.Model):<br>    receiver = models.EmailField()<br>    content  = models.TextField(max_length=500)<br>    sent = models.BooleanField(default=False)<br>    created_date = models.DateField(auto_now_add=True)<br>    <br>    def __str__(self):<br>        return self.receiver</pre><p><strong>2. Write a Command:</strong></p><p>Back to <strong>my_command.py</strong> and change it in this way:</p><pre>from django.core.management.base import BaseCommand, CommandError<br>from django.core.mail import EmailMessage<br>from my_app.models import Report</pre><pre>class Command(BaseCommand):<br>    help = &quot;Execute to send all unsent reports&quot;</pre><pre>    def handle(self, *args, **options):<br>            try:<br>                reports = Report.objects.filter(sent=False)<br>                if reports.exists():<br>                     for report in reports:<br>                         subject = &#39;Report&#39;<br>                         receiver = report.receiver<br>                         content = report.content<br>                         new_email = EmailMessage(<br>                         subject, content,<br>                        &#39;youremailaddress&#39;, [receiver])</pre><pre>                         new_email.send(fail_silently=False)<br>                         report.sent = True<br>                         report.save()<br> <br>             except Exception as e:<br>                raise CommandError(e)</pre><p>In this example, we took all unsent reports and send them.</p><p>In some cases, you may want to send a specific report. For that purpose, we will add the <strong><em>add_arguments </em></strong>function to the Command class. Now the class should look like that:</p><pre>from django.core.management.base import BaseCommand, CommandError<br>from django.core.mail import EmailMessage<br>from my_app.models import Report</pre><pre>class Command(BaseCommand):<br>     help = &quot;Execute to send all unsent reports&quot;</pre><pre>     def add_arguments(self, parser):<br>        parser.add_argument(&#39;report_ids&#39;, nargs=&#39;+&#39;, type=int)</pre><pre>     def handle(self, *args, **options):<br>           for id in options[&#39;report_ids&#39;]:<br>                try:<br>                   report = Report.objects.get(id=id)<br>   <br>                except Report.DoesnNotExist:<br>                   raise CommandError(&#39;Report doesn not exist&#39;)<br>  <br>                subject = &#39;Report&#39;<br>                receiver = report.receiver<br>                content = report.content<br>                new_email = EmailMessage(<br>                    subject, content,<br>                   &#39;youremailaddress&#39;, [receiver])<br>                 new_email.send(fail_silently=False)<br>                 report.sent = True<br>                 report.save()</pre><p>The first attribute inside <strong><em>add_aruments</em></strong> shows us how we can access the ids in the <strong><em>handle </em></strong>function.</p><p>Call this command with a specific id:</p><pre>py manage.py my_command &lt;report_ids&gt;</pre><p>You can send one id or even a list of ids</p><h3>Conclusion</h3><p>At the end of the tutorial, we learned how to custom management commands in different ways and execute them. Write below if you have any questions</p><blockquote>Thanks for reading. Stay tuned for more ✌</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d66044c37433" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/writing-custom-management-commands-in-django-d66044c37433">Writing Custom Management Commands in Django</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Telegram Bot with Scheduled Tasks]]></title>
            <link>https://medium.com/analytics-vidhya/python-telegram-bot-with-scheduled-tasks-932edd61c534?source=rss-750455dcf7c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/932edd61c534</guid>
            <category><![CDATA[scheduling]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[telegram-bot]]></category>
            <dc:creator><![CDATA[Rafael Salimov]]></dc:creator>
            <pubDate>Sun, 28 Feb 2021 15:39:49 GMT</pubDate>
            <atom:updated>2023-05-10T07:32:25.291Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*B1XxqXxkoQk5kCP2" /><figcaption>Image source: <a href="https://github.com/python-telegram-bot/python-telegram-bot">here</a></figcaption></figure><p>Hello. In this tutorial, we will learn how to create a simple echo bot in python with some Scheduled tasks. Let’s begin!</p><h3>Dependencies and First Steps:</h3><p>There is a list of all dependencies you should have for this tutorial:</p><ol><li>Python</li><li>Telegram account</li><li>python-telegram-bot module</li></ol><p>Probably, you already have the first 2 dependencies, so let’s begin with the installation of the module. Open terminal and type this command:</p><pre>pip install python-telegram-bot</pre><p>Then we have to create our bot and get the token from Telegram. For that open telegram and search for “BotFather” (“@BotFather”). Choose the verified one. Type start to view all possible commands, the bot should respond to you like that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*LhR0R4I9Z5yfJXQfwP17Ag.png" /></figure><p>Type <strong><em>/newbot</em></strong> to create a new bot. This will be the next response of BotFather. Choose the name and unique username for your bot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*BMjJ5yvbf27ruF7nabTzNg.png" /><figcaption>I chose <strong>BotForTutorial </strong>for this case and “@<strong>MediumTutorialBot</strong>” as username</figcaption></figure><p>If everything is okay, BotFather will send you a response like below in the picture with token and credentials. Do not share your token with anyone, it is like a <strong><em>secret key</em></strong> in Django. I will delete the bot after the tutorial, so I am going to show you my credentials:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*QJgJnk_hYuVKz0Ugsb1HJg.png" /></figure><p>As you can see we created our bot and we can find it with the link or just by searching in Telegram. Now you can add a profile picture, description, and so on to your bot. Feel free to do that, but now we are focused to code our bot. Let’s continue.</p><h3>Development</h3><p>Open any editor and let’s begin!</p><p>First, we have to import some modules from <strong><em>python-telegram-bot</em></strong>:</p><pre><em>from</em> telegram.ext <em>import</em> Updater, CommandHandler<br><em>import</em> logging</pre><p><strong><em>Updater </em></strong>will get all updates that happing with our bot (messages and so on). We are using <strong><em>logging </em></strong>to show errors and <strong><em>CommandHandler </em></strong>to handle all commands that we are going to create. Let’s create our <strong><em>updater</em></strong>:</p><pre>updater = Updater(token=&#39;1605329753:AAGy9Hukl7Nc8CzUJ0tcfndxR_tctvKDCRI&#39;, use_context=True)</pre><pre>dispatcher = updater.dispatcher</pre><pre>logging.basicConfig(format=&#39;%(asctime)s - %(name)s - %(levelname)s - %(message)s&#39;, level=logging.INFO)</pre><p>Let’s write our first command for the bot. Obviously, it will be /<strong><em>start </em></strong>command.</p><pre># writting functionality of the command<br>def start(update, context):<br>    message = &#39;Welcome to the bot&#39;<br>    context.bot.send_message(chat_id=update.effective_chat.id, text=message)</pre><pre># give a name to the command and add it to the dispaatcher<br>start_handler = CommandHandler(&#39;start&#39;, start)<br>dispatcher.add_handler(start_handler)</pre><pre>updater.start_polling() // enable bot to get updates</pre><p>Now run the script and go check the command in the telegram.</p><p>As you see, we used <strong><em>update.effective_chat.id</em></strong> to send a message to a specific user. But what if we want to send a message to all our users? Unfortunately, this API does not provide something like that, so we will store all our users in our database. You can use any database, I will use a remote Redis database. You also can get a free Redis database from <a href="https://heroku.com/">Heroku</a>.</p><p>I assume you get a URL to your Redis database. To use it, we have to install Redis on our machine:</p><pre>pip install redis</pre><p>How will we store it? The most effective way to do it, to store the user’s username and id when the user types /<strong><em>start </em></strong>command. First, add these lines to the script:</p><pre><em>from</em> telegram.ext <em>import</em> Updater, CommandHandler<br><em>import</em> logging<br>import redis</pre><pre>r = redis.from_url(https://medium.com/&#39;your_redis_db_url&#39;) # connection to the databse<br>db_keys = r.keys(pattern=&#39;*&#39;)   # allows us to fetch data</pre><p>Then rewrite the <strong><em>start </em></strong>function in this way:</p><pre>def start(update, context):<br>    user_id = update.message.from_user.id<br>    user_name = update.message.from_user.name<br>    r.set(user_name, user_id)</pre><pre>message = &#39;Welcome to the bot&#39;<br>    context.bot.send_message(chat_id=update.effective_chat.id, text=message)</pre><p>You can check the list of subscribers any time you want. Create new script <strong><em>users.py:</em></strong></p><pre><em>import</em> redis<br>r = redis.from_url(https://medium.com/&#39;your_redis_db_url&#39;)<br>db_keys = r.keys(pattern=&quot;*&quot;)<br>print((len(db_keys)))</pre><pre><em>for</em> single <em>in</em> db_keys:</pre><pre>    chat_id = r.get(single).decode(&quot;UTF-8&quot;)<br>    print(single.decode(&quot;UTF-8&quot;), &quot;: &quot;, chat_id)</pre><p>Let’s now write an <strong><em>echo </em></strong>function to allow the bot to send to the user the same message he/she sent to the bot. Import Filters and MessageHandler to handle messages from <strong><em>telegram.ext</em></strong> and write function below:</p><pre>def echo(update, context):<br>    context.bot.send_message(chat_id=update.effective_chat.id, text=update.message.text)</pre><pre>from telegram.ext import MessageHandler, Filters<br>echo_handler = MessageHandler(Filters.text &amp; (~Filters.command), echo)<br>dispatcher.add_handler(echo_handler)</pre><blockquote>Note: That is not a command and you cannot access it by typing /<strong><em>echo</em></strong>. It is automatical handler that will reply to the user after the user’s text message (with the help of <strong><em>Filters.text</em></strong>)</blockquote><h3>Scheduled Jobs/Tasks:</h3><p>In order to use scheduled tasks, we use <strong><em>job_queue</em></strong>. It has several methods as <strong><em>run_once</em></strong>, <strong><em>run_daily</em></strong>, and others. In this case, we will use these two methods.</p><p>First, we should add <strong><em>job_queue </em></strong><em>to the</em><strong><em> updater. </em></strong><em>We will use</em><strong><em> CallbackContext </em></strong><em>here also, so import it from</em><strong><em> telegram.ext</em></strong></p><pre>j = updater.job_queue</pre><p>As it seems from the name of the method, <strong><em>run_once </em></strong>runs the command only once. We decide the time and command will be automatically ran by <strong><em>run_once</em></strong>.</p><p>Let’s write the function we want to be executed only once:</p><pre>def once(context: CallbackContext):</pre><pre>    message = &quot;Hello, this message will be sent only once&quot;<br>    <br>    # send message to all users<br>    <em>for</em> keys <em>in</em> db_keys:<br>        id = r.get(keys).decode(&quot;UTF-8&quot;)<br>        context.bot.send_message(chat_id=id, text=message)</pre><p>Now add that function to <strong><em>run_once </em></strong>and give time:</p><pre><em>j.run_once(once, 30)</em></pre><p><strong><em>run_once </em></strong>takes two attributes, the function we want to execute and time. 30 means that the function will be executed 30 seconds after deployment</p><p>Let’s move to <strong>run_daily. </strong>Write morning function like that:</p><pre>def morning(context: CallbackContext):</pre><pre>    message = &quot;Good Morning! Have a nice day!&quot;<br>    <br>    # send message to all users<br>    <em>for</em> keys <em>in</em> db_keys:<br>        id = r.get(keys).decode(&quot;UTF-8&quot;)<br>        context.bot.send_message(chat_id=id, text=message)</pre><p>Now add that function to <strong><em>run_daily </em></strong>and make configurations:</p><pre>job_daily = j.run_daily(morning, days=(0, 1, 2, 3, 4, 5, 6), time=datetime.time(hour=10, minute=00, second=00))</pre><p><strong><em>run_daily </em></strong>takes several attributes: the function we want to be executed, days(it should be a tuple), and time (import <strong><em>datetime</em></strong>). This function will be executed every day at 10:00 and users will get a “Good morning” message.</p><h3>Finally:</h3><ol><li>You can get more detailed information about all possible commands and methods available on python-telegram-bot from its official blog. Click <a href="https://python-telegram-bot.readthedocs.io/en/stable/">here</a></li><li>You can join their telegram group and find answers to your questions. Click <a href="https://web.telegram.org/#/im?p=@pythontelegrambotgroup">here</a></li><li>If you want to deploy this script (for example on Heroku) you can read my article about it from <a href="https://thesaintraphael.medium.com/hosting-python-script-on-heroku-b5eb4dc28606">here</a>.</li></ol><blockquote>Write below if you have some questions. Thanks for reading!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=932edd61c534" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/python-telegram-bot-with-scheduled-tasks-932edd61c534">Python Telegram Bot with Scheduled Tasks</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>