Honestly, I have long thought whether to publish this material. For those who know how to work with AMI Asterisk, there is nothing interesting here. For those who are just starting to do something, they are unlikely to figure it out in my code (although I tried to write clearly). Vanguyu comments like: "Why use Habr for your notes?". On the other hand, the script given under the cut can be someone's starting point. The script does nothing except that it sends to the console all the events from AMI and is able to filter them. For example, I show all calls in the console that fall into any of the contexts “zadarma-in” or “sibseti_in”. If interested, please under the cat:
There was a real-time task to look at which trunk the call came from, which buttons in ivr the user clicked, who answered the call, etc. I have long wanted to try to work with AMI from Python, before that I had a little experience from Bash and then to organize a call back.
Having rummaged with various ready-made libraries, it quickly came to the realization that none of them suits me. As a result, his “bicycle” was invented in the form of a script, which gives all the information from AMI to json. Uses standard Python libraries. Plus the fact that in this form it is easy to receive and parse any events and not to lose binding to a specific call.
The first script prints only those events that fall into any of the contexts "zadarma-in" or "sibseti_in".
Script number 1import telnetlib import json import re
And the second script, which writes all events to the console, looking at both scripts, it becomes clear what needs to be changed in order to achieve the desired result. If it is not completely clear, then parsit needs json "string [mes]" in the function "def telnet_for_string (string)":
Script number 2 import telnetlib import time import json import re