Giter Club home page Giter Club logo

robbot's Introduction

Maintainability Rating Quality Gate Pass Lines of Code License image image CodeSize image image image Image GitHub commits since latest release (by date) image

Robbot

IT/ENG

This Telegram bot has the same structure of this project which is an userbot I made for several features I needed.
So this bot has some commands in common with that userbot but also other new commands and obviously there aren't those commands that a bot can't execute but a userbot can.
So if you're interested you can also visit that repository.


Feel free to contribute and improve the project.
See more details on How to contribute here.

After the Italian section you will find an english version of the README. In doc folder you will find a bit of documentation of RobBot.

[IT]

Come impostare

Per un corretto funzionamento è necessario compilare a dovere il file config.json. Quindi è necessario essere in possesso dei seguenti dati:

  • Api keys di Telegram: api_id e api_hash. Puoi generarle da qui
  • Bot token: bot_token. Puoi generarlo da qui
  • Api url atm se si vogliono usare le loro api: api_url , api_get e cookie. (Non essendo pubbliche non le condividerò)
  • Api key di OpenWeatherMap: api_weather. Puoi generare la tua key dal sito principale di OpenWeatherMap
  • Api di OpenAI: api_openai. Puoi generare la tua key dal sito principale di OpenAI
  • I dati telegram dell'amministratore del bot: id_super_admin.
  • Il percorso dove si trova il file .db: path_db.
  • Nome della sessione: session_name.
  • I nomi dei comandi utente, admin e superadmin: user_commands, admin_commands e super_admin_commands.

I dati del super admin servono a colui che potrà usare le funzioni di interazione con il database e altre funzioni particolari. I nomi dei comandi da inserire nel config.json possono essere ricopiati dal codice oppure possono essere modificati sul codice e poi ricopiati nel file json.

Se siete su un'ambiente totalmente a linea di comando e vi accedete in ssh, consiglio il seguente comando per avviare il bot:

python3 app.py 2>&1 > /dev/tty1 &

Come funzionano i comandi utente del bot

Il funzionamento dei comandi utente è spiegato all'interno del file help.json. Si tratta del file che viene usato dal bot per rispondere al comando /helprob <nome comando>. Le spiegazioni sono in Italiano, ma volendo si possono tradurre in qualsiasi lingua sostituendo i campi della struttura dati oppure addirittura renderlo multilingua, ma in quel caso c'è da sviluppare la componente che rende possibile il cambio di lingua.

Come funzionano i comandi admin e super

  • registrare un nuovo utente: /setrobuser <id_utente>
  • registrare un nuovo admin: /setrobadmin <id_utente>
  • cancellare un utente: /delrobuser <id_utente>
  • revocare i privilegi admin: /delrobadmin <id_utente> (l'utente sarà comunque ancora tra i registrati ma senza i poteri admin)
  • mostrare tutti gli utenti registrati: /listrobuser
  • mostrare il numero di utenti registrati: /allrobuser
  • verificare se il bot è online: /pingrob
  • registrare un nuovo gruppo come unico autorizzato a ricevere un certo comando: /setgroup <id_gruppo>
  • cancellare un gruppo salvato: /delgroup <id_gruppo>
  • mostrare tutti i gruppi salvati: /listgroup
  • modificare un valore nelle statistiche di un utente per un certo comando: /updatestat <id_utente> 'comando' <nuovo_valore>
  • cancellare un comando dalle statistiche di un utente: /delstat <id_utente> 'comando'
  • Aggiornare i dati Telegram di un utente(nome e username): /updaterobuser <id_utente> (oppure dando lo username)
  • Aggiornare il credito di un utente per l'utilizzo di openai: /amount <id_utente>
  • Visualizzare l'elenco degli utenti che hanno del credito di utilizzo per openai: /allamounts
  • Riavviare il bot direttamente da Telegram senza passare dalla shell: /restart
  • Inviare un messaggio a un utente registrato: /say ; 'messaggio'

Dipendenze

  • Pyrogram
  • tgcrypto
  • peewee
  • utils_config
  • geopy
  • bs4
  • wikipedia
  • pandas
  • matplotlib
  • openai
  • urbandictionary
  • pdf2image
  • pytube
  • flightradar24
  • FlightRadarAPI
  • pokebase
  • wikipediaapi

Progetti esterni usati

[ENG]

How to setup

The correct way to setup this bot is to compile the file config.json. So it's necessary to have these data:

  • Telegram api keys: api_id e api_hash. You can generate them here
  • Telegram bot token: bot_token. You can generate it from here
  • Atm api url if you wanna use their api: api_url , api_get and cookie. (The api are not public so I won't share them here)
  • OpenWeatherMap api key: api_weather. You can generate your key from the OpenWeatherMap website.
  • OpenAI api key: api_openai. You can generate your key from the OpenAI website.
  • Telegram data of the owner of the bot: id_super_admin.
  • The path where is the .db file: path_db.
  • The session name: session_name.
  • Name of user commands, admin commands and super admin commands: user_commands, admin_commands e super_admin_commands.

Data of super admin is needed because he's the only one who can use db functions and other special functions. Name of commands to put inside config.json can be copied from source code or renamed inside source code and then copied in json file.

How the user bot's commands works

The features of the user commands are explained inside help.json. It is the file which is used by the bot to reply at /helprob <command name>. This json file is only in Italian, but you can translate it in every languages by changing the correct fields with your translations or even making the bot multi-language but in that case you have to develop the component for change the language runtime.

If you're in a command-line env and you access with ssh, I suggest the following command to start the bot:

python3 app.py 2>&1 > /dev/tty1 &

How the admin/super commands works

  • register a new user: /setrobuser <id_user>
  • register a new admin: /setrobadmin <id_user>
  • delete a user: /delrobuser <id_user>
  • delete an admin: /delrobadmin <id_user> (it will just revoke the admin power, it doesn't delete the user)
  • How to list all user registered: /listrobuser
  • How to show ho many users are registered: /allrobuser
  • check if the bot is online: /pingrob
  • Save a new group to make it the only one authorized to receive a specific command: /setgroup <id_group>
  • Delete a saved group: /delgroup <id_group>
  • Show all saved groups: /listgroup
  • Update a value in a user's stat for a specific command: /updatestat <id_user> 'command' <new_value>
  • Delete a command from a user's stat: /delstat <id_user> 'command'
  • Update user's Telergam data(name and username): /updaterobuser <id_user> (or giving username)
  • Update the user's credit for openai usage: /amount <id_user>
  • Show all user and their openai credit: /allamounts
  • Restarting the bot directly in Telegram without manually doing in shell: /restart
  • Sending a message to a registered user: /say <id_user> ; 'message'

Dependencies

  • Pyrogram
  • tgcrypto
  • peewee
  • utils_config
  • geopy
  • bs4
  • wikipedia
  • pandas
  • matplotlib
  • openai
  • urbandictionary
  • pdf2image
  • pytube
  • flightradar24
  • FlightRadarAPI
  • pokebase
  • wikipediaapi

External projects used

robbot's People

Contributors

archetipico avatar mastercruelty avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

Forkers

mariolzz

robbot's Issues

🚀 Improve listrobuser

At this time /listrobuser shows every user who is subscribed to use bot's commands.

It's possible to improve this command to show in a group only the users inside that group and subscribed to the bot.

In a private chat with the superadmin the bot should show again all the users

/getmessage doesn't work

The command /getmessage which return the json of a Telegram message doesn't work anymore for some reason.
Maybe it's because of an update of Pyrogram or something else(more probably).

I'll close this issue as soon as I fix it.

❌ /atm isn't working cause 403

Since yesterday, it's impossibile to fetch data anymore because of 403 error. Unless I find another solution, this command will never work again.
This affect atm_feature.py source file.
So also #33 will never be done.

[3.0] 🚀 Improve wikipedia search

Sometimes the returned page isn't the required one.

A wrapper I found on GitHub here.

  • Try out the wrapper and decide if it's better than the current library.
  • Improve the search of pages.
  • Refactor code.

[2.0] 📑 /atm timetables as photo

  • Try to convert subway timetable from the pdf web link to an image thus we can send it directly instead of clicking the link.
  • The same thing in case the waiting time is None.

[2.0] ⏩ Refresh button /atm command

Now we have InlineKeyboards working in this bot and a useful feature would be to put a refresh button after we type /atm 'stop_code'.
Thanks to this, there won't be need to launch again the command to see the updated wait time, you just press the refresh button.

🐛 /edatm doesn't work anymore

Atm website changed route for resale points.
So it's needed to adapt the /edatm function to the new route.
File to edit

edit: no route has changed. the CustomerCode parameter of all resale object is null for some reason.
Anyway there is another route to get resale objects, so it can be fixed one day.

🐛 Check needed in reminder.py

It's needed to do a check when result is equal to zero because the bot would reply immediately even if you type a wrong input.

🚀 /mystat improvement

It would be better not showing /mystat in the list of commands used.
Then another improvement can be an order by in the SQL query

[2.0] 🚀 Use of DALL-E

Openai has another service about generating images with AI using DALL-E algorithm.

  • Studying how it works.
  • A command /aimg that send an image generated by DALL-E.(Integrated in modules/openai.py)
  • Use of davinci-003 instead of 001(it seems to be more powerful)
  • Add an edit text command
  • Add a pay as you go system to give certain number of resource to givers

♻️ 🚀 Improve /vaccine

The json files this command fetch data from are becoming too large to read and compute them. The raspberry Pi freezed/crashed after two commands launched in the same moment.
There is the need to modify /vaccine to read the .csv files located in the same repository.

🚀 More weather commands

Just dropping here a couple of ideas for other weather commands:

  • A command that post a weather map by using wttr.in
  • A command that post a weather map by using sat24.com

🚀 Improve /searchatm

It would be cool to update this command to filter a single stop instead of dropping all the line.

example:
/searchatm M2 0, lanza
and it should return only the data about lanza stop with direction 0

[2.0] 🥼 Logging directly in Telegram

  • Using visualizza function to send message log to a specific chat on Telegram(probably a private channel)
  • Sending also errors if occured to the same chat.

🐛 Fix /listrobuser

If you type the command in private chat with the bot, it doesn't return the entire list of registered users.
The query have to be fixed

[3.0] 🧪 Add test

  • Adding test structure source files
  • Adding test for main functions
  • Adding test for utility functions

[2.0] 📖 Update doc

  • Update of the LaTeX documentation because of the recent update of db.
  • Check if other sections have to be updated

[2.0] OpenAI feature

  • A command that use OpenAI API to give a random reply to a string input
  • A way to choose the max length of the reply (2048 is the API limit) (not necessary)
  • A way to choose which engine of OpenAI use

This command should be used only by a few users(such as admin as you can see in dbtables.py) considering the API isn't free

Redesign database

The current database is using different tables with same fields. It's necessary to redesign the entire database.
see the tables here

And after that there is to modify also the db functions

[2.0] Trenitalia api

A few commands to show timetable of the Italian train you look for.

  • A command to check information about a specific train(delay etc.etc.)
  • A command to fetch data and show the next trains coming in a station by giving departure and arrival station
  • Showing ticket price
  • Showing the last detection of a train

[Fix] /searchsongs long message

If an artist has too many song the message will be larger than 4096 which is the Telegram limit for a single message.

Solving #15 can solve this problem.

[3.0] 📈 More stats about commands used

For example which artist you common search on /lyrics

  • db table to modify: Stats in utils/dbtables.py
  • function to modify: update_stats() and show_stats() in utils/dbfunctions.py
  • Choice for the type of graph in /mystat

/vaccine doesn't work anymore

The repository where Robbot takes data has been modified.
Inside the file somministrazioni-vaccini-summary-latest.json there isn't anymore the field categoria_over80 but only the fascia_anagrafica

The quickest way to fix this is to delete every reference to the field that doesn't exists anymore.

the code with references to that field:

for item in data_somministrazioni:      
    if(query =="/vaccine"):            
        over80 += item["categoria_over80"]           
        prima_dose += item["prima_dose"]            
        seconda_dose += item["seconda_dose"]        
    else:         
        if(query.title()[0:4] in item["nome_area"]):                
            over80 += item["categoria_over80"]               
            prima_dose += item["prima_dose"]              
            seconda_dose += item["seconda_dose"]
for i in range(len(fornitori)):      
    forn_str += "**" + fornitori[i] + ":** __" + format_values(fornitori_somma[i]) + "__\n"  
result = "Dati complessivi sui vaccini in __**" + regione + "**__ :\n**__Ultimo aggiornamento: " + giorno + "__**\n\n**Dosi consegnate:** __" + format_values(total_consegne) + "__\n**Dosi somministrate:** __" + format_values(total_somm) + "__\n**Percentuale dosi somministrate:** __" + str(perc) + "%__\n**Over 80 vaccinati:** __" + format_values(over80)

[2.0]♻️ Refactor /wiki

  • Refactor the comune function to get also the "Curazia" type of comune.
  • Refactor the amount of time it edit the message to avoid the sleep exception raised by Telegram API.
  • Refactor the wiki function to make /wiki to give a random page instead of calling /wiki random

Handle exception in wiki.py

Sometimes it happens an error that it could be handled.

The exception raised is requests.exceptions.ConnectionError

This is an example of the error with input vim editor di testo in the function: exec_wiki_ita(query,client,message)

raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPConnectionPool(host='vim.wikipedia.org', port=80): Max retries exceeded with url: /w/api.php?list=search&srprop=&srlimit=1&limit=1&srsearch=editor+di+testo+&srinfo=suggestion&format=json&action=query (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x74378910>: Failed to establish a new connection: [Errno -2] Name or service not known'))

[3.0] 🚀 Favorite stops

  • Add user data about favorite stops in db.
  • Add a command to save and get favorite stops data(mono space text or buttons).
  • Add a command to delete a favourite stop

These tasks are intended for /atm and /tper commands.

Security bug

def isAdmin(id_utente):
    if isSuper(id_utente):
        return True
    else:
        check = User.select().where(User.id_user == id_utente and User.admin == True)
        for admin in check:
            return True
        return False

In pewee and doesn't work. It's necessary to use &

📑 More documentation

As the project keep being larger, it's necessary to add more documentation for functions and the main functioning of the bot such as how it starts and how the main process works from getting the input to send the output on Telegram.
It can be an occasion also to refact something if needed as said also in #43 .

[*.0] 🐛 Fix conflict between two different buttons

Typing /urban argument1 and then /urban argument2 will be resulting in a conflict because if you press the button of the first command you get the next page of argument1 but if you press the button of the second command, you get still the next page of argument1 instead of argument2.

I used /urban as an example but the problem is intended in every function that uses Inline buttons.

urban.py

🚀 Improve /lyrics

It would be cool to add a couple of features to /lyrics command.
For example /lyrics System Of A Down could return the list of albums and titles of all songs or /lyrics Metallica, kill em all could return the list of songs inside the kill em all album.

If needed it's also possible to refactor some pieces of code.

[2.0] Tper api

A few commands to check Tper bus and trains in Emilia-Romagna

  • A command to check stop info by giving stop code
  • A command to check trains by giving station code or searching the station

[2.0] Urban Dictionary feature

  • A command which fetch data from Urban Dictionary
  • A way to choose which definition should be showed between the results.

[2.0] 🎮 Trivial command

  • a command which fetch trivial questions from https://opentdb.com/
  • A leaderboard of users that made more correct questions
  • /trivial to get a question multiple choice random category and random difficulty
  • /trivial tf easy category to fetch a true/false question on difficulty easy on a chosen category(multi instead of tf for a multiple choice)

[2.0] 🗺️ more maps feature

  • Using folium module to show map pics
  • Possibility of showing pin on a certain point on the map
  • Choropleth map
  • Improving /map using location.address, location.raw["type"] and location.raw["importance"] as caption of the message

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.