<?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 Russian Hacker on Medium]]></title>
        <description><![CDATA[Stories by Russian Hacker on Medium]]></description>
        <link>https://medium.com/@RussianHacker?source=rss-f18778247e82------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*QPGkCrXe0vC8iTg4lnR4Cg.png</url>
            <title>Stories by Russian Hacker on Medium</title>
            <link>https://medium.com/@RussianHacker?source=rss-f18778247e82------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 09:09:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@RussianHacker/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[Instagram bot to improve your personal life]]></title>
            <link>https://medium.com/@RussianHacker/instagram-bot-to-improve-your-personal-life-7351e573524?source=rss-f18778247e82------2</link>
            <guid isPermaLink="false">https://medium.com/p/7351e573524</guid>
            <category><![CDATA[relationships]]></category>
            <category><![CDATA[automatization]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Russian Hacker]]></dc:creator>
            <pubDate>Mon, 07 Feb 2022 13:29:38 GMT</pubDate>
            <atom:updated>2022-02-07T13:29:38.224Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently my girlfriend and I had a serious conversation and it turned out that I don’t even text her “Good morning” and I rarely text in the morning at all. In general, the reason is that I do not wake up with the first sunrise (as she does), and I do not like to text very much. Well, she, of course, enjoys receiving tenderness in the morning and all that.</p><p>Since we communicate exclusively on Instagram, I thought it would be nice to combine all that and automate the process. Especially since the social network seems to have an open API.</p><p>As it turned out, there is no full-fledged official API there, and the one that is there only supports business accounts. But one way or another, I wanted to try it.</p><blockquote>I am sure that there are services for that, but I wanted to make my own working bot. I found an article on Habra about sending messages in PHP, from which I took the address to send a request (link to article in the end). And here I will try to describe essentially the same process, but in Python. Same bot, with minimal functions. Maybe someone may find it useful.</blockquote><blockquote>Full code and README on Github and below are the key points.</blockquote><h3>Script scheme</h3><p>In order to organize the code and some way to expand functionality in the future, the script is divided into 3 classes:</p><ol><li>Login — is responsible for authorization and creates the session;</li><li>MessageMaker — message generation;</li><li>SendMsg — direct sending of a message.</li></ol><p>And additionally, 2 configuration files <em>auth.txt</em> and <em>conf.txt</em>: authorization data and dictionary with messages respectively and startup <br>manager — <em>insta_bot_manager.py</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*j7EAoFHTXjDdWAqB.png" /><figcaption>Structure of the directory</figcaption></figure><h3>Login class — authorization</h3><p>Let’s see how Instagram authorization works. To do this, look at the outgoing requests directly in the browser tools:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XesKNSCqzuQavvRKjDrD3g.png" /></figure><p>As you can see — the request is sent to <a href="https://www.instagram/%20.com/accounts/login/ajax/"><em>https://www.instagram .com/accounts/login/ajax/</em></a>, and it looks pretty simple. There are no tokens or any left parameters. Except the password is encrypted. As I found out, it’s AES-GCM256 encoding, obviously with some kind of prefix. The query string looks like this:</p><p>#PWD_INSTAGRAM_BROWSER:10:16940921:enc_password#PWD_INSTAGRAM_BROWSER:10:16940921:enc_password</p><p>The parameter “10” stands for the encrypted password, followed by the time and the password itself. Of course, I’m not going to make my own encryption tool, but there is another way to sign in with the password in cleartext. To pass the plain string, just replace “10” with “0”:</p><p>#PWD_INSTAGRAM_BROWSER:0:1690149:password</p><p>The file used to store authorization data is <em>auth.txt</em>. I know that it is better to store it all in encrypted form, but since the data is only on the server — it is relatively safe.</p><p>The construction of the <em>auth.txt</em> looks like this:</p><ol><li>Login</li><li>Password</li><li>Ig_user_id (user id of the user to whom we are sending the message)</li></ol><p>Just text. Each parameter must be written on a new line. We read from the file:</p><pre>with open(“auth.txt”, “r”) as f: <br>  l = f.read().split(“\n”) <br>  username = l[0] <br>  passwd = l[1] <br>  self.user_id = l[2]</pre><p>Now we login using <strong>requests</strong>:</p><pre><strong><em># First, let&#39;s get a csrf-token: </em></strong><br>r = requests()  </pre><pre><strong><em># You can use a piece of the full authorization link or make a <br>request directly to https://www.instagram.com/. </em></strong><br>login_url = &quot;https://www.instagram.com/accounts/login/&quot;  </pre><pre><strong><em># You can specify your user-agent in the headers. In the other case, the security alert in the application comes, which you&#39;d better confirm. <br># If the User-Agent header is missing or has some garbage in it, IG responds with a &quot;message&quot; error: &quot;user-agent missmatch&quot;.  </em></strong></pre><pre><strong><em># Because the simulated session - immediately change the user-agent directly in the object of the session.</em></strong> <br>s = request.Session() <br>s.headers[&quot;User-Agent&quot;] = <br>  (&quot;Mozilla/5.0 (iPhone; CPU iPhone OS 14_1 like Mac OS X) &quot; +<br>  &quot;AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 Instagram<br>  142.0.0.22.109&quot; + <br>  &quot;(iPhone12,5; iOS 14_1; en_US; en-US; scale=3.00; 1242x2688;<br>  214888322) NW/1&quot;)  </pre><pre><strong><em># And, actually, the request itself </em></strong><br>get_token = r.get(login_url, headers=headers)  </pre><pre>if get_token.cookies.get(&quot;csrftoken&quot;) is not None:   <br>  headers[&quot;x-csrftoken&quot;] = get_token.cookies[&quot;csrftoken&quot;]  <br> <br>  <strong><em># If you can&#39;t get the token out of the cookie, try another way </em></strong>else:   <br>  if csrf_token.get(&quot;success&quot;) != None:     <br>    headers[&quot;x-csrftoken&quot;] = csrf_token.get(&quot;value&quot;)     <br>    if csrf_token.get(&quot;error&quot;):       <br>      return csrf_token</pre><p>Send a POST request with the received data:</p><pre>login = r.post(login_url + “ajax/”, data=auth_data, headers=headers)</pre><pre><strong><em># The status of the operation can be checked by parsing the response from the server. <br># If the status value is &#39;ok&#39; in the response dictionary, and the UserId is present, all is well. <br># But, for simplicity, you can see if the &quot;sessionid&quot; cookie is set </em></strong>if log_in.cookies.get(&quot;sessionid&quot;):  <br>  return {&#39;success&#39;: &#39;ok&#39;, &#39;response&#39;: log_in.content}</pre><p>The full answer should look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*kzIbaaNGHtluk1E-HC116A.png" /><figcaption>Successful authorization attempt response</figcaption></figure><h3>Looking for a csrf-token manually</h3><p>If IP, agent, password, and probably some other client parameters change, Instagram starts asking for confirmation of cookie policy. Accordingly, there is no cookie, there is no token and normal POST request is impossible.</p><p>If you look at the text representation of the response to the first GET-request at /accounts/login/- you can find the token in the authorization form.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*LNlLQZSPTYZEHkeKHQrD_A.png" /><figcaption>csrf-token in response. 19 BC.</figcaption></figure><p>To search, let’s make a simple regular expression(regex) that will not work only with this answer:</p><pre>import re  </pre><pre>def response_parse(self, response):  <br>  if response is not None:   <br>    token = re.search(&#39;(csrf_token&quot;:&quot;)+(?P&lt;value&gt;[A-Za-z0-9]*)&#39;,<br>    response)   <br>    token_value = token.groupdict()        </pre><pre>    if token_value is not None:    <br>      return {&quot;success&quot;: &quot;ok&quot;, &quot;value&quot;: token_value.get(&quot;value&quot;)}  </pre><pre>    return {&quot;error&quot;: &quot;Unable to extrack token from response!&quot;}</pre><p>As a rule, it works only for the first attempt, after changing the parameters. For some reason, after authorization cookies start to be issued as usual. BUT, it is important to keep an eye on the value of the token — after a successful request it will change in the cookie and, it is good to overwrite it.</p><h3>“Smart” message selection</h3><p>Since the bot was created for the sole purpose of sending messages to a girl in the morning, it would be worth adding some “brains” to it. In general, the message selection scheme looks pretty trivial — the list of available phrases from the file is read and the cherished one is randomly selected.</p><p>Since the script will be triggered every day, and messages of the “Good morning, already at work?” — It is better to make sure that such messages are not sent on weekends, and vice versa.</p><p>To do this, create a <em>conf.txt</em> dictionary with the suggested phrases in the folder next to the script and come up with the simplest syntax for it. It occurred to me to mark weekend messages with “@” symbol, weekdays — “!”, and to send messages every day without marking. Well, and comments (where without them) with “/”. Dictionary example:</p><pre>Good morning to you &lt;3  </pre><pre>! <br>Hi, how did you get to work? <br>!  </pre><pre>@ <br>Good morning, what are your plans for the day? <br>@     </pre><pre><br><strong><em>// Comment here. This is not handled at all</em></strong></pre><h3>Dictionary processing and pseudorandom selection</h3><p>The MessageMaker class will take care of the message selection. In the constructor we will add only — with as — to read the dictionary:</p><pre>def __init__(self):  <br>  with open(&quot;conf.txt&quot;, &quot;r&quot; as get_f:   <br>    self.get_f = get_f.read().split(&#39;\n&#39;)</pre><p>To determine the day of the week we can use datetime.today().weekday():</p><pre>day = datetime.today().weekday()  </pre><pre><strong><em># If it&#39;s the weekend </em></strong><br>if day &gt; 4:  <br>  get_phrase = self.array_sort(array=self.get_f, symbol=&quot;!&quot;)    </pre><pre><strong><em># If it&#39;s a weekday </em></strong><br>if day &lt; 5:   <br>  get_phrase = self.array_sort(array=self.get_f, symbol=&quot;@&quot;)<br>  get_random_str = random.choice(get_phrase)</pre><p>Function array_sort() takes 2 parameters: an array of strings from <em>conf.txt</em> and a delimiter whose messages to ignore. The result will be a new, sorted list, from which any phrase can be randomly selected (function random.choice())</p><p>The sorting itself looks terrible like this:</p><pre>def array_sort(self, array, symbol):<br>  new_array = []<br>  counter = 0</pre><pre>  for string in array:<br>    if counter &gt; 0:<br>      <strong><em># Zero the counter if we see the same symbol again</em></strong><br>      if string == symbol:<br>        counter = 0<br>        continue<br>      <br>    <strong><em># Skip all lines between the specified separators</em></strong><br>    if string == symbol:<br>      counter += 1</pre><pre>    <strong><em># If the conditions are met, we add the string to a new array<br>    # containing only available phrases</em></strong><br>    if string != symbol and len(string) &gt; 2 and string[0] != &quot;/&quot;:<br>      new_array.append(string)</pre><pre>  return new_array</pre><p>Now let’s add a main function that returns directly the selected string:</p><pre>def select_str(self):<br>  get_random_str = self.almost_random_choice()</pre><pre>  if get_random_str != &#39;&#39; and get_random_str != None:<br>    return get_random_str</pre><pre>  return self.select_str()</pre><p>Since Instagram itself escapes characters and converts any type to str — there is no need to force them manually.</p><p>Test run select_str():</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*vKl159_h0jntYOUGC9lLIg.png" /><figcaption>Message Selection</figcaption></figure><h3>SendMsg — direct sending of a message</h3><p>In the SendMsg class — Login and MessageMaker. And also let’s add the initialization of parent classes to the constructor:</p><pre>class SendMsg(Login, MessageMaker):<br>  def __init__(self, enc_password=False):<br>    super().__init__(enc_password=enc_password)<br>    MessageMaker().__init__()</pre><p>And, directly, send the message, using all the functionality. Create a send_message() function with optional parameters:</p><pre>def send_message(self, random_msg=None):<br>  pass</pre><p>If the message is specified directly in the function call, no data is read from the file, and vice versa. The random_msg parameter takes any string you want to send as a message.</p><p>Log in and create a session:</p><pre>log_in = self.login()</pre><p>If the function returned success in the dictionary, then we can continue:</p><pre>if log_in.get(&quot;success&quot;) is not None:<br><strong>  <em># Begin</em></strong></pre><p>Define a set of parameters to send a POST request:</p><pre><strong># link to send a message. I found it on Habra and some other site.</strong><br>send_mess_to_url =  &quot;https://i.instagram.com/api/v1/direct_v2/threads/broadcast/text/&quot;  </pre><pre><strong><em># We generate a new uuid v4. This is also standard Python functionality </em></strong><br>uuid_v4 = uuid.uuid4()   </pre><pre><strong><em># Let&#39;s check how the message is formed. If the parameter has been set - it is used </em></strong><br>if random_msg is None:  <br>  message = self.select_str()  </pre><pre>else:  <br>  message = str(random_msg)  <br>  enc_message = message.encode(&quot;utf-8&quot;)  </pre><pre><strong><em># The body of the query. We put all the parameters into it. </em></strong><br>body = (&#39;text={}&amp;&#39; +<br>         &#39;_uuid=&amp;&#39; +<br>         &#39;_csrftoken={}&amp;&#39; +<br>         &#39;recipient_users=&quot;[[&quot;{}&quot;]]&quot;&amp;&#39; +<br>         &#39;action=send_item&amp;&#39; +<br>         &#39;thread_ids=[&quot;0&quot;]&amp;&#39; + <br>         &#39;client_context={}&#39;).format(enc_message.decode(&quot;latin-1&quot;),<br>          self.session.cookies[&quot;csrftoken&quot;], user_id, uuid_v4) <br>  <br><strong><em># And all the headlines </em></strong><br>headers = self.session.headers <br>headers[&quot;Content-Type&quot;] = &quot;application/x-www-form-urlencoded&quot; headers[&quot;x-csrftoken&quot;] = self.session.cookies[&quot;csrftoken&quot;]  </pre><pre><strong><em># The Ig-App-ID can be found in the headers of Instagram requests. It changes from time to time, but not often. </em></strong><br>headers[&quot;X-IG-App-ID&quot;] = &quot;936619743392459&quot;</pre><p>Later I will add the X-IG-App-ID check function. Because it is returned in the headers after successful authorization. It’s not hard to check the values and update them if needed.</p><p>And send the request:</p><pre>send_m = self.session.post(send_mess_to_url, data=body,<br>         headers=headers)</pre><p>It is also desirable to define a simple logging function, just to simplify debugging. Since the script runs on the server, it is good to record everything that happens:</p><pre>def _log(*args, **kwargs):<br>  if args:<br>    for i in args:<br>      string = string + &#39; &#39; + str(i)</pre><pre>  if kwargs:<br>    for key, value in kwargs:<br>      string = string + &#39; &#39; + str(value)</pre><pre>  with open(&quot;log.log&quot;, &quot;a&quot;) as f:<br>    print(string, file=f)</pre><p>Run it and look at the log:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*VVztRFLkSBdrzg9HGFAshg.png" /><figcaption>The message was sent to my second account</figcaption></figure><p>The message has been sent. You can see the date sent, the status code and the text that was sent. This is enough to identify problems or to make the selection of the message not only random, but also dependent on the previous day.</p><h3>Launch Manager</h3><p>For ease of launching, create a script manager — insta_bot_manager.py and place it in the folder next to insta_bot.py.</p><p>Let’s place the handler function and import the written module:</p><pre>from insta_bot import SendMsg<br>import os</pre><pre>def __send__(enc_password=None, random_msg=None):<br>  <strong><em># Create an instance of the class</em></strong><br>  s = SendMsg(enc_password=enc_password)<br>  <br>  <strong><em># Sending a message </em></strong><br>  return s.send_message(random_msg=random_msg)</pre><pre>if __name__ == “__main__”:  <br>  <strong><em># You can add optional parameters enc_password and random_msg</em></strong><br>  __send__()</pre><p>As well as checking the existence of the <em>auth.txt</em> file. Because it makes no sense to run all this without authorization data:</p><pre>def _conf_check():<br>  file_check = os.path.exists(<br>               os.path.dirname(<br>               os.path.abspath(__file__)) + &quot;/auth.txt&quot;)</pre><pre>  if not file_check:<br>    raise Exception(&quot;You must create/or fill the auth.txt file!&quot;)</pre><pre>  return 1</pre><p>Now if <em>auth.txt</em> is missing for some reason, the exception will be raised.</p><h3>Automating the process in Cron</h3><p>Since I didn’t want to add <em>insta_bot_manager.py</em> to the bash shebangs, I decided to just make another launcher specifically for Cron.</p><p>In the folder with the script, create a file <em>launcher</em>:</p><p>$ touch launcher &amp;&amp; nano launcher</p><p>Let’s add something like this:</p><pre><strong><em>#!/bin/bash</em></strong><br>sleep $[RANDOM%70]m <br>/usr/bin/python3.6 /home/path/to/insta_bot.manager.py</pre><p>The script falls asleep for a random time of up to 70 minutes before launching itself.</p><p>In general, when adding to cron, it is worth watching out for environment variables. In particular the PWD. I was getting errors because of the difference in home directory and the folder with the script. To fix it, you can stick as the first command cd with the full path to the folder.</p><h3>Conclusions</h3><p>It’s worth being careful, because such a mailing is not exactly legal and, sort of, you can grab Instagram’s banhammer in the face. However, as it seems to me, sending 1–2 messages a day to the same ID will not cause suspicion. Personally, I haven’t received any warnings in a few weeks of using the bot, but anyway.</p><p>I don’t know the girl’s reaction to this. On the one hand — the bot is made with love and sends pleasantries, on the other — it might be seen as insincere. But so far things are good, let’s see what happens next. Perhaps in the future I will have to send voice messages :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*Es1njAl4yy3fSOk6t1qjsg.png" /><figcaption>Example of work</figcaption></figure><p><a href="https://github.com/palachintosh/insta_bot">Code on GitHub</a></p><p><a href="https://habr.com/ru/post/486714/">Link to Habra article</a></p><blockquote><strong>Author:</strong> @Palachintosh <br><strong>Original article: </strong><a href="https://habr.com/ru/post/579732/">https://habr.com/ru/post/579732/</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7351e573524" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>