Package: telegram-payment-bot
Telegram Payments BotTelegram bot for handling payments in groups based onpyrogramlibrary.Payments data can be loaded either from anxls/xlsxfile or from a Google Sheet (in this way, it can be shared with other admins).It is also possible to extend this to load payments data from other sources (e.g. a remote database) by inheriting and implementing thePaymentsLoaderBaseclass, but I didn't need to do it so far.Payments data can be updated either manually by the admins or, better, automatically (e.g. by the website where the payment is made, via a webhook). It depends on the infrastructure you have.SetupCreate Telegram appIn order to use the bot, in addition to the bot token you also need an APP ID and hash.To get them, create an app using the following website:https://my.telegram.org/apps.InstallationThe package requires Python 3, it is not compatible with Python 2.To install it:Usingsetuptools:python setup.py installUsingpip:pip install telegram_payment_botTo run the bot, edit the configuration file by specifying the API ID/hash and bot token. Then, move to theappfolder and run thebot.pyscript:cd app
python bot.pyWhen run with no parameter,conf/config.iniwill be the default configuration file (in this way it can be used for different groups).To specify a different configuration file:python bot.py -c another_conf.ini
python bot.py --config another_conf.iniOf course, theappfolder can be moved elsewhere if needed.ConfigurationAn example of configuration file is provided in theapp/conffolder.The list of all possible fields that can be set is shown below.NameDescription[pyrogram]Configuration for pyrogramsession_nameSession name of your choiceapi_idAPI ID fromhttps://my.telegram.org/appsapi_hashAPI hash fromhttps://my.telegram.org/appsbot_tokenBot token from BotFather[app]Configuration for appapp_is_test_modeTrue to activate test mode false otherwiseapp_lang_fileLanguage file in XML format (default: English)[users]Configuration for usersauthorized_usersList of Telegram usernames that are authorized to use the bot, comma separated[support]Configuration for supportsupport_emailEmail for getting support or send payments receipts (default: empty)support_telegramTelegram username for getting support or send payments receipts (default: empty)[payment]Configuration for paymentpayment_websiteWebsite for payment (default: empty)payment_check_on_joinFlag to check the payment of new members as soon as they join the group (default:true)payment_check_dup_emailFlag to check for duplicated emails in payment data (default:true)payment_typeInput for payment data:EXCEL_FILEfor using xls/xlsx file,GOOGLE_SHEETfor using a Google Sheetpayment_excel_fileName of the Excel file used for payment data, loaded only ifpayment_typeisEXCEL_FILEpayment_google_sheet_idID of the Google Sheet used for payment data, loaded only ifpayment_typeisGOOGLE_SHEETpayment_google_cred_typeCredentials type:OAUTH2for OAuth2 flow orSERVICE_ACCOUNTfor service account (default:OAUTH2), loaded only ifpayment_typeisGOOGLE_SHEETpayment_google_credName of thejsoncredentials file for OAuth2 or service account (default:credentials.json), loaded only ifpayment_typeisGOOGLE_SHEETpayment_google_cred_pathPath where Google OAuth2 token file will be saved, loaded only ifpayment_typeisGOOGLE_SHEETandpayment_google_cred_typeisOAUTH2payment_use_user_idIf true,payment_user_colwill be considered as a user ID (number), otherwise it'll be considered as a usernamepayment_worksheet_idxWorksheet index (default:0)payment_email_colTable column (letter) containing the email used for paying (default:A, maximum:Z)payment_user_colTable column (letter) containing the user (default:B, maximum:Z). The user can be a username or a user ID (depending on thepayment_use_user_idflag).payment_expiration_colTable column (letter) containing the payment expiration date (default:C, maximum:Z)payment_date_formatDate format in payments data (default:%d/%m/%Y)[email]Configuration for email that reminds users to payemail_enabledEmail enable flag (default:false). If false, all the next fields will be skipped.email_fromEmail senderemail_reply_toEmail reply-toemail_hostHost for sending emailemail_userUsername for logging to hostemail_passwordPassword for logging to hostemail_subjectEmail subjectemail_alt_bodyFile containing email alternate body (text)email_html_bodyFile containing email HTML body[logging]Configuration for logginglog_levelLog level, same of python logging (DEBUG,INFO,WARNING,ERROR,CRITICAL). Default:INFO.log_console_enabledTrue to enable logging to console, false otherwise (default: true)log_file_enabledTrue to enable logging to file, false otherwise (default: false). If false, all the next fields will be skipped.log_file_nameLog file namelog_file_use_rotatingTrue for using a rotating log file, false otherwiselog_file_max_bytesMaximum size in bytes for a log file. When reached, a new log file is created up tolog_file_backup_cnt. Valid only iflog_file_use_rotatingis true.log_file_backup_cntMaximum number of log files. Valid only iflog_file_use_rotatingis true.log_file_appendTrue to append to log file, false to start from a new file each time. Valid only iflog_file_use_rotatingis false.Supported CommandsList of supported commands:help: show help messagealive: show if bot is activepaybot_set_test_mode true/false: enable/disable test modepaybot_is_test_mode: show if test mode is enabledpaybot_auth_users: show the list of authorized users that can use the botpaybot_chat_info: show the chat information (can be run only in group)paybot_users_list: show the users list (can be run only in group)paybot_invite_link: generate a new invite link (can be run only in group)paybot_version: show the bot versionpaybot_check_username [<HOURS_LEFT>]: show the list of chat members without a username (can be run only in group)HOURS_LEFT(optional): hours left to set the username before being removed (only for printing the message). Hours are automatically converted to days if greater than 47. If less than 1, it'll print "as soon as possible". Default value: 0.paybot_remove_username: remove all the chat members without a username (can be run only in group)paybot_set_check_on_join true/false: enable/disable payment check when a new member joinspaybot_is_check_on_join: show if payment check when a new member joins is enabledpaybot_check_data: check payments data for errors (e.g. invalid dates, duplicated users) and show thempaybot_email_payment [<DAYS_LEFT>]: send a reminder email to chat members whose payment is expiring in the specified number of daysDAYS_LEFT(optional): number of days within which the payment expires. Less than 1 means expiring today. Default value: 0.paybot_check_payment [<DAYS_LEFT>] [<LAST_DAY>]: show the list of chat members whose payment is expiring in the specified number of days (can be run only in group)DAYS_LEFT(optional): number of days within which the payment expires. Less than 1 means expiring today. Default value: 0.LAST_DAY(optional): last day to complete the payment before being removed (only for printing the message). If less than 1 or greater than 31, it'll print "within few days". Default value: 0.paybot_remove_payment: remove the chat members whose payment has expired (can be run only in group)paybot_task_start PERIOD_HOURS: start payment check task with the specified periodPERIOD_HOURS: task period in hourspaybot_task_stop: stop payment check taskpaybot_task_info: show payment check task informationpaybot_task_add_chat: add the current chat to the payment check taskpaybot_task_remove_chat: remove the current chat from the payment check taskpaybot_task_remove_all_chats: remove all chats from the payment check taskAddquietorqas last parameter to send the bot response in a private chat instead of the group chat.Users removed from the group are just kicked and not banned, so they can re-join later via invite links if necessary.When users are removed from the group (either because they had no username or they didn't pay), a new invite link is generated and sent to all authorized users in a private chat.This automatically revokes the old invite link and prevents those users to join again using it.When checking for payments, a user is removed from the group if:He has no Telegram usernameHis Telegram username or user ID is not found in the payments dataHis payment is expiredIfpayment_check_dup_emailis set to true:If multiple rows have the same email address, only the first row will be loaded and all the others will be skipped (therefore, those users won't be considered as valid payments)Rows with duplicated email address will be printed by thepaybot_check_datacommandPayment Check TaskIt's suggested to run a background task to check for payments periodically. It can be started/stopped with thepaybot_task_start/paybot_task_stopcommands.The task can check multiple groups in one time (sharing the same payments data, of course). The groups can be added/removed with thepaybot_task_add_chat/paybot_task_remove_chatcommands (either while the task is running or stopped).If no group was added, the task will simply run without checking any group.The period of the task always starts from midnight (if you use a VPS, be sure to set the correct time), for example:A task period of 8 hours will check for payments at 00:00, 08:00 and 16:00A task period of 6 hours will check for payments at 00:00, 06:00, 12:00 and 18:00Run the BotThe bot shall be an administrator of the group.If you just need to run bot once in a while (e.g. once a week), you can do it manually using thecheck_no_paymentandremove_no_paymentcommands. In this case, it's sufficient to run the bot locally on the PC when needed.If you prefer to let the bot check for payment periodically, it'll be better to run it 24h/24h on a VPS.Payment FileThe payment file can be either axls/xlsxfile (xlrdlibrary is used) or a Google Sheet.In case a Google Sheet is used and the OAuth2 flow is chosen:Create a project onGoogle Cloud ConsoleGo toAPIs & Services, thenCredentialsand selectConfigure Consent ScreenCreate a new app and publish it, it doesn't need to be verified (but you can verify it, of course)Go back to theCredentialspage and create the credentials for OAuth client ID by selectingCreate CredentialsSelectDesktop app, choose a name and download thejsonfile with the credentialsGo to theLibrarypage, search for Google Sheet and enable Google Sheet APIsRename thejsonfile to the name specified in the configuration file (payment_google_cred) and place it in theappfolderThe first time the bot loads your Google Sheet, you'll be asked to login into your Google account and allow the bot to access the sheet. After this, a newjsonfile will be automatically created in the folder you configured (payment_google_cred_path).Thisjsonfile allows the bot to access the sheet next times, so you don't need to allow it againIf you move the bot to another PC or server, just keep thejsonfiles to grant the bot access to the sheet without repeating the whole procedureFor more information:create project,create credentialsSince for allowing the bot to access the Google Sheet a browser window will open, in case of a dedicated server (no GUI) it's easier to generate thejsonfile on a PC and then just copy it to the server.Alternatively, you can create a service account, which is pre-authorized. In this case, you don't need to authorize it from the browser window but you only have to share the Google Sheet with the service account gmail.In both cases (Google Sheet or Excel file), the file shall contain the following columns starting from the second row (the first row is used as header):Email address used for paying (for convenience, since an email address is usually required in payment platforms)Telegram user ID or usernameExpiration date of the payment in the format specified bypayment_date_formatThe indexes of these columns are set in the configuration file. It is possible to add other columns beside these if necessary, they are simply ignored by the bot.Test ModeTest mode can be used to test the bot without any effect to the users of the group. When active:Users are not kicked from the group if they don't have a username or don't have paid, in any case (i.e. when running a command, when joining the group, during periodical checks)Emails are not sent to the users that haven't paid yetMoreover, the payment task period will be applied in minutes instead of hours. This allows to quickly check if it is working.Channel LimitationsWhen used in channels:The bot can check for payments periodically but it cannot check users immediately when they joinAll admins can use the bot, not only authorized usersCommands in quiet mode will send the result to authorized users instead of privately to the user that executed the commandDue to a Telegram limitation, only 200 members can be managedTranslationThe messages sent by the bot on Telegram can be translated into different languages (the default language is English) by providing a custom XML file.The XML file path is specified in the configuration file (app_lang_filefield).An example XML file in italian is provided in the folderapp/lang.LicenseThis software is available under the MIT license.