Saravanan666/pypi-org huggingface dataset:
Package: telegram-autoconv
Welcome to Autoconv!A Python package that help you build complex Telegram bot conversations with buttons, actions and much more.This package is built over the awesomePython-Telegram-Bot!SetupYou can find the package onPyPi (pip).pip3 install telegram-autoconvRequirementsPython 3.9+python-telegram-bot 13+ExamplesI know you want examples, in fact there is a beautiful folder with someexamples.In the table below, you can find an example for every functions in the module.In addition to that, there is a live Telegram bot to showcase every features,@AutoBot.FunctionExampleDocumentationadd_keybordkeyboards.pyStateadd_textactions.pyStateadd_dynamic_textactions.pyStateadd_actionactions.pyStateadd_dynamic_keybordkeyboards.pyStateadd_custom_keyboardkeyboards.pyStateadd_dynamic_routeskeyboards.pyStateadd_dynamic_listdynamic_list.pyStateadd_custom_handlerhandlers.pyStateset_long_taskactions.pyStateadd_refresh_authauthorization.pyStateadd_operation_buttonskeyboards.pyStateConversationconversation.pyConversationadd_routesconversation.pyConversationset_defaultsdefaults.pyConversationadd_authorized_usersauthorization.pyConversationstate_messagestexts.pyTexts Guideset_timed_functionasync.pyAutoConvHandlerstop_timed_functionasync.pyAutoConvHandlersend_autodestroy_messageasync.pyAutoConvHandlerrestartautoconv_handler.pyAutoConvHandlerforce_stateautoconv_handler.pyAutoConvHandlersavetdata.pyTelegamDataaddtdata.pyTelegamDataget_or_settdata.pyTelegamDataPersistenceIf you want to use persistence in your bot, Autoconv provides a simple persistence based on PicklePersistence.The normal PicklePersistence doesn't work, due to an instance of aTelegram.Messagein theuser_data, this persistence uses a workaround.fromautoconv.utils.persistenceimportAutoconvPersistencepersistence=AutoconvPersistence(filename="bot_persistence",bot_token=BOT_TOKEN)updater=Updater(BOT_TOKEN,persistence=persistence)WARNING! This persistence will save the bot token in a pickle file.DocumentationDo you want to read? I got you cover, baby!No more than a little documentation in theWiki.Real World ExampleI have a simple movies info Telegram bot publicy available.You can interact with the Bot (the response time it kinda high, caused by very slow connection)PopCorn(sorry for the italian).The code (except for the config files) is in thisGIST.Do you want to help me?If you want to contribute you are welcome! I don't have guidelines for now, but contact me on Telegram@Mortafix.If you want to donate, thank you so much for your support!
Package: telegram-bell
telegram-bellNotify you when something is mentioned in a telegram channel.Installpip install telegram-bellUsageCLIRuntbell runBefore you can use, it will ask you for:your Telegram API IDyour Telegram API hashchannels and keywords which you want to get notifiedTelegram token (2FA)The app will then forward the matching messages to your "Saved Messages" channel in Telegram over time.Configtbell configYou can reconfigure the application at any time with this command.Show susbscribed channelstbell showSystemd user serviceClone the repo and:cd telegram-bell/scripts
sh install_service.sh
sh start_service.sh # it will ask you for configCheck the service is running:sh check_service.shYou can check the services logs too:sh show_service_logs.shIf the service fails or the machine is restarted, the service will run transparently again.If you want to change your config in some moment:tbell config
sh restart_service.sh
Package: telegrambot
Despite this code having been in production in quite a heavy use
environment for a good few months, I really wouldn’t class it as an
example of great code.It would be fair to say I got sidetracked, and decided to see how much I
could abuse certain aspects of Python (such as metaclasses/class
creation).You have been warned!With that out of the way,telegrambotis pretty easy to get up and
running.% pip install telegrambot
% cat mybot.cfg
[core]
bot_id = <telegram_bot_id>
token = <telegram_bot_token>
[bing]
key = <bing_api_key>
% telegrambot mybot.cfgAs it stands the framework exposes three commands;/crashand/hangwere used to test error handling and threading during
development whereas/getis a bring-your-own-api-key bing image
searcher.Adding plugins aims to be really easy, just create a namespace package
undertelegrambot.pluginsand subclasstelegrambot.plugins.base.BasePlugin(now that I think about it, the
namespace package may not be necessary - I will have to re-think my
motivation on that one).Example Pluginfromtelegrambot.plugins.baseimportBasePlugin# due to annoying limitations class names must be uniqueclassHelloWorld(BasePlugin):# register /hello command to 'hello_handler' methodcommands{'hello':'hello_handler'}defhello_handler(self,args,msg):# `args` is a list of the arguments after the command:# '/hello world' -> args=['world']# `msg` is a dictionary representing the Telegram `Message` object# see TelegramAPIMixin for available Telegram API functionsself.send_message('Hello,{}'.(' '.join(args)),msg['chat']['id'],reply=msg['message_id'])
Package: telegrambotapiwrapper
What is telegrambotapiwrapper?telegrambotapiwrapperis Telegram Bot Api implementation for PythonRequirementscpython: 3.7, 3.8, 3.9Installationpip install telegrambotapiwrapperGetting started.Creating a botYou mustcreate a bot and get a tokenTesting your bot's auth tokenWe use the methodgetMe:>>>fromtelegrambotapiwrapperimportApi>>>first_bot_api=Api(token="<paste your token here>")>>>me=first_bot_api.get_me()>>>meUser(id=123456679,is_bot=True,first_name='botbotbot',last_name=None,username='myrudatingposterbot',language_code=None)Check result type:>>>fromtelegrambotapiwrapper.typelibimportUser>>>isinstance(me,User)TrueSending a text message to channelPreconditionsBefore sending a text message to a channel, you must:create channeladd bot to channel as administratorget channel idSending to the channel>>>first_bot_api.send_message(chat_id=-12345678912345,text="sdjfhjsdfbjdbvhj")Message(message_id=299,date=1558966491,chat=Chat(id=--12345678912345,type='channel',title='FooFoo',username='lalalalalalala',first_name=None,last_name=None,all_members_are_administrators=None,photo=None,description=None,invite_link=None,pinned_message=None,sticker_set_name=None,can_set_sticker_set=None),from_user=None,forward_from=None,forward_from_chat=None,forward_from_message_id=None,forward_signature=None,forward_sender_name=None,forward_date=None,reply_to_message=None,edit_date=None,media_group_id=None,author_signature=None,text='sdjfhjsdfbjdbvhj',entities=None,caption_entities=None,audio=None,document=None,animation=None,game=None,photo=None,sticker=None,video=None,voice=None,video_note=None,caption=None,contact=None,location=None,venue=None,poll=None,new_chat_members=None,left_chat_member=None,new_chat_title=None,new_chat_photo=None,delete_chat_photo=None,group_chat_created=None,supergroup_chat_created=None,channel_chat_created=None,migrate_to_chat_id=None,migrate_from_chat_id=None,pinned_message=None,invoice=None,successful_payment=None,connected_website=None,passport_data=None)Note that chat_id is negative.Sending a photo to channel>>>withopen('/home/dzmitry/Pictures/500800998.jpg','rb')asimage:...first_bot_api.send_photo(chat_id=-12345678912345,photo=image,...caption="hello world")>>>Note the open file mode.Method and typesImplemented all methods Telegram Bot ApiImplemented all types Telegram Bot ApiAll types of Telegram Bot Api are imported from thetypelibmodule.LicenseMIT License
Copyright (c) 2020 Dzmitry MaliuzhenetsSee LICENSE for details.
Package: telegram-bot-deploy
telegram-bot-deploytelegram-bot-deployissimpleandeasy-to-usescript that perform continuous deployment for theTelegram bots.InstallationYou can installtelegram-bot-deployfromPyPi:pip install telegram-bot-deployor from GitHub:pip install https://github.com/ciotto/telegram-bot-deploy/archive/master.zipHow to useYou can usetelegram-bot-deploywith the commandtbd -u git@github.com:your/repo.git.There are many configurable parameters. You can see all configuration using commandtbd -h.Is also possible to use environments variables or a.envfile in order to set basic configuration.The available variables are:REPO_URL: The URL of the repo to be usedREPO_PATH: The local path of the repoBRANCH: The branch used for deploySSH_KEY: The SSH key to be used to authenticate to the repoCHAT_ID: The chat ID used for bot communicationBOT_TOKEN: The bot token used for bot communicationMSG_CREATE_VIRTUALENV_FAIL: Message that will be send when create virtualenv failMSG_INSTALL_REQUIREMENTS_FAIL: Message that will be send when install requirements failMSG_RUN_TESTS_FAIL: Message that will be send when run tests failMSG_COVERAGE_FAIL: Message that will be send when get coverage failMSG_COVERAGE_LOW: Message that will be send when coverage is too lowMSG_RESTART_FAIL: Message that will be send when bot restart failMSG_NEW_VERSION: Message that will be send when new version was deployedPID_FILE_PATH: The path to the PID filePYTHON_EXECUTABLE: The Python executableVIRTUALENV_PATH: The path to the Python virtualenvCREATE_VIRTUALENV: The command used in order to create the Python virtualenvREQUIREMENTS_PATH: The path to the requirements fileINSTALL_REQUIREMENTS: The command used in order to install the requirementsRUN_TESTS: The command used in order to run the testsMIN_COVERAGE: The minimal coverage required in order to deployGET_COVERAGE_PERCENTAGE: The command used in order to get the coverage percentage valueRUN_BOT: The command used in order to run the botLOGGING_FORMAT: The format for Python loggingLOGGING_LEVEL: The level for Python loggingLOGGING_FILENAME: The filename for Python loggingHow to contributeThis is not a big library but if you want to contribute is very easy!clone the repositorygit clone https://github.com/ciotto/telegram-bot-deploy.gitinstall all requirementsmake initdo your fixes or add new awesome features (with tests)run the testsmake testcommit in new branch and make a pull requestYou chan usetelegram-bot-deploydevelopment version with the commandpython -m bot_ci.LicenseReleased underMIT License.
Package: telegram-bot-gpt
Telegram-Bot-GPTA simple interface for OpenAI GPT-3 and GPT-4 using Telegram bots.DISCLAIMERThis open-source module is only intended to provide an interface between bot and AI on top of the following services:Bot provided for free by Telegram FZ-LLCGPT AI capabilities as paid services from OpenAI LPThe creator of this library isnot in any way responsiblefor any misuse of the module, including but not limited toany costs that may occurdue to calls to the GPT AI.Using this library states that you are agree with this disclaimer.Installationpip install telegram-bot-gptUsageimport bot_gpt as bot

mybot = bot.Engine("<YOUR_TELEGRAM_TOKEN>")
mybot.set_openai_key("<YOUR_OPENAI_KEY>")  # a filename also accepted

mybot.run()     # only polling method is providedThat's it!!Special FeaturesAdmin now has access to GPT-4Using global OTP, changeable and resetable by adminA small number of chats are stored encrypted as bot memoryUsed tokens are recorded along with the model, useful for cost calculationModifiable bot parametersDev FunctionsSettingsThe variablebot.DEFAULT_SETTINGcontains a dict of the initial values of accessible configurations:{
  "memory_length": 3,        # the number of previous lines involved
  "ai_temperature": 85,      # 0.75 in the API input
  "bot_active": 1,           # 0 is deactivated
  "daily_limit": 50,         # daily usage limit for common users, server time
  "admin_limit": 999,        # daily usage limit for admin, server time
  "password": ""             # will be set automatically at first run
}Accessing variables:mybot.set_daily_limit(100)modify valuemybot.reset_daily_limit()reset to defaultcurrent_daily_limit = mybot.get("daily_limit")obtain the valuemybot.reset_settings()reset all values to defaultBot namemybot.set_botname("My Bot")
mybot.reset_botname()        # default is "Bot-GPT"OpenAI keymybot.set_openai_key("<YOUR_OPENAI_KEY_OR_CORRESPONDING_FILENAME>")
mybot.del_openai_key()       # AI capabilities will be deactivatedMemory length, only used when the input is shortmybot.set_memory_length(5)   # more value leads to a more expensive cost
mybot.reset_memory_length()  # default is 3
memory_length = mybot.get_memory_length()Bot UsageAdminThe first user is automatically set as the bot admin which is equipped with a list of commands such as password regulations and bot activations.PasswordNew users should enter a randomized code (password) created by the bot which can only be accessed by admin with these commands:/get_passworddisplays the current password/new_passowrdchanges the password without affecting current users/reset_passwordforce all users to enter the new password to continue using the botDeactivationThe default setting for bot isactive, whereas only admin has the right to modify it./deactivate_botbot is off for all users, whileadmin still can use it/activate_botreactivates the bot for all usersAll users can check the bot status using/is_bot_active.How To GetTelegram BotOpen Telegram app, chat with@BotFatherand send the command /newbot.OpenAI keyLogin toOpenAIand follow the instructions there.
Package: telegram-bot-logger
Telegram Bot LoggerTelegram Bot Logger is a Python library that allows you to send logging logs to Telegram using the Bot API. It simplifies the process of integrating Telegram bot notifications into your Python applications, making it easy to monitor and manage your application's logs.InstallationYou can installtelegram_bot_loggerusing pip:pipinstalltelegram-bot-loggerUsageimporttelegram_bot_loggerimportlogginglogger=logging.getLogger("telegram_bot_logger_example")handler=telegram_bot_logger.TelegramMessageHandler(bot_token="YOUR_BOT_TOKEN",# Required; bot's token from @BotFatherchat_ids=[12345678,"@username"],# Required; you can pass id as integer or username as stringapi_server=telegram_bot_logger.api_server.TelegramAPIServer(base="https://api.telegram.org/bot{bot_token}/{method}"),# Optional; set by defaultformat_type="text"or"TEXT"ortelegram_bot_logger.formatters.FormatType.TEXT,# Optional; also can be "DOCUMENT", by default it is "TEXT"document_name_strategy="timestamp"or"TIMESTAMP"ortelegram_bot_logger.formatters.DocumentNameStrategy.TIMESTAMP,# Optional; used to define documents' names; also can be "ARGUMENT", by default it is "TIMESTAMP"proxies={"http://":"http://localhost:8080"}or"http://localhost:8080",# Optional; "dict[scheme, url]" or just "url"formatter=formatters.TelegramHTMLTextFormatter(),# Optional; you can create your own class inherited from formatters.TelegramBaseFormatter and pass itadditional_body={"reply_to_message_id":1}# Optional; additional request body on sendMessage and sendDocument)logger.setLevel(level=logging.DEBUG)logger.addHandler(handler)logger.debug("debug-message")# Or:logger.debug("debug-message",extra={"document_name":123})# 123 is an argument; to use this feature you need to set format_type = formatters.FormatType.DOCUMENT and document_name_strategy = formatters.DocumentNameStrategy.ARGUMENTReplaceYOUR_BOT_TOKENandchat_idswith your actual bot token and chat IDs. You can obtain a bot token by creating a new bot on Telegram and obtaining it from theBotFather.Stay UpdatedFor the latest news and updates, follow myTelegram Channel.
Package: telegrambot-py
telegrambot-pyMake your own telegram bot easily.Getting StartedBefore starting, you need to create a bot and get a token for it. For details, see instructionshere.Below is the example code that responds 'pong' for '/ping' command.fromtelegrambotimportBotbot=Bot('your_bot_token')@bot.command('/ping{name}')defping(ctx,name):return"Hello,{}".format(name)bot.start()DevelopmentPrerequsitesPython 3.5 or greaterPipenvInstall dependenciespipenvinstall--devRunning Testspipenvrunlint
pipenvruntestDeploymentpipenvrunpackage
Package: telegram-bottools
Create Telegram BotTelegram -> BotFather -> Type/newbothttps://core.telegram.org/bots/tutorial#creating-your-commandGet Chat IDhttps://api.telegram.org/botXXXX:YYYYY/getUpdatesInstallpip install telegram-bottoolsConfigbot_config = (chatid, token)Quick Startfrom telegram_bottools import telegram_bottools as bot


bot_config = (-11111111, 'xxxxxx:yyyyyyyyyyy')
message = 'Hello World!'

bot.send_message(*bot_config, message)
Package: telegram-bot-unittest
Unit-tests forpython-telegram-bot.How it worksThis is a first version of libraryOnly long polling mode supported!Library starts your python-telegram-bot object with custom url (our unit-test server on Flask running under waitress).
Now you can communicate in unit-tests with your bot as you do in Telegram.Featuressend text messagesend commandsend filereceive fileFixturesuserUser object to send messages and check incoming messages from your botbotYour bot object. See ‘Using’Echo Bot exampleCheck echo of Echo Bot from python-telegram-bot example.def test_echobot_message(bot, user):
    user.send_message('testing message')
    message = user.get_message()
    assert message['text'] == 'testing message'Check /start command of Echo Botdef test_echobot_start(bot, user):
    user.send_command('/start')
    message = user.get_message()
    assert message['text'] == 'Hi [FN LN](tg://user?id=1)\!'File Bot exampleBot renames file you send to him.def test_echobot_file(bot, user):
    current_dir = os.path.dirname(os.path.abspath(__file__))

    user.send_document(current_dir, 'test.txt')

    document = user.get_document()

    file_io = document.path_or_bytes
    assert file_io.name == 'echo_test.txt'

    content = io.TextIOWrapper(file_io, encoding='utf-8').read()
    assert content == 'Hello world!\nHello world!'InstallingYou can install or upgrade telegram-bot-unittest with:$ pip install telegram-bot-unittest --upgradeOr you can install from source with:$ git clone https://github.com/dontsovcmc/telegram-bot-unittest --recursive
$ cd telegram-bot-unittest
$ python setup.py installUsing1. Create non-bloking function ‘setup_bot’ that runs your bot.
We need to separate updater.idle() and creating Updater().def setup_bot(bot_token: str, base_url: str = None) -> Updater:

    updater = Updater(bot_token, base_url=base_url)

    dispatcher = updater.dispatcher

    dispatcher.add_handler(CommandHandler("start", start))
    dispatcher.add_handler(CommandHandler("help", help_command))
    dispatcher.add_handler(MessageHandler(Filters.text & ~Filters.command, echo))
    updater.start_polling()

    return updater

def main(base_url: str = None) -> None:

    updater = setup_bot(BOT_TOKEN, base_url)
    updater.idle()Add fixture ‘bot’ to you fixture.py file. Example:import pytest
from <your module> import <start_bot_function>
from telegram_bot_unittest.routes import TELEGRAM_URL
from telegram_bot_unittest.user import BOT_TOKEN

@pytest.fixture(scope='session')
def bot(telegram_server):
    updater = start_bot_function(BOT_TOKEN, TELEGRAM_URL)
    yield updater.bot
    updater.stop()add ‘telegram_bot_unittest.fixtures’ to ‘pytest_plugins’ list in conftest.pyAdd fixture ‘bot’ to you test functions.Enjoy!ContributingContributions of all sizes are welcome.LicenseYou may copy, distribute and modify the software provided that modifications are described and licensed for free underLGPL-3. Derivatives works (including modifications or anything statically linked to the library) can only be redistributed under LGPL-3, but applications that use the library don’t have to be.
Package: telegram-botup
Telegram-botupPython library for building Telegram botsInstall$ pip install telegram-botupExample# app.pyfromweb_libimportApp,Requestfrombotup.dispatcherimportDispatcherfrombotup.apiimportApifrombotup.typesimportBaseContextTOKEN="token"app=App()api=Api(TOKEN)dispatcher=Dispatcher()@dispatcher.message_handler('hello')asyncdefhello_handler(ctx:BaseContext):awaitapi.send_message(ctx.chat_id,f'Hello{ctx.update.message.from_.first_name}')@app.post(f'/{TOKEN}')asyncdefindex(request:Request):awaitdispatcher.handle(awaitrequest.json())return""Widgets example# app.pyfromasyncioimportgatherfromweb_libimportApp,RequestfrombotupimportWidget,Context,Dispatcher,Api,Bot,Navigationfrombotup.widgets.date_pickerimportDatePickerfrombotup.mixins.echoimportEchoMixinfrombotup.typesimportInlineKeyboardMarkup,InlineKeyboardButtonTOKEN="token"WEBHOOK=f'https://url/{TOKEN}'classTestMixin:defbuild(self,dispatcher:Dispatcher):dispatcher.register_command_handler('/test',self.cmd_test)@staticmethodasyncdefcmd_test(ctx:Context):awaitctx.api.send_message(chat_id=ctx.chat_id,text='Test')classRootWidget(Widget,TestMixin,EchoMixin):asyncdefentry(self,ctx:Context,**kwargs):botup_date_picker_result=kwargs.get(DatePicker.DEFAULT_RESULT_KEY)ifbotup_date_picker_result:awaitctx.api.send_message(chat_id=ctx.chat_id,text=f'date:{botup_date_picker_result}')returndefbuild(self,dispatcher:Dispatcher):TestMixin.build(self,dispatcher)dispatcher.register_command_handler('/start',self.cmd_start)dispatcher.register_callback_handler('ready',self.clb_ready)EchoMixin.build(self,dispatcher)@staticmethodasyncdefcmd_start(ctx:Context):message=awaitctx.api.send_message(chat_id=ctx.chat_id,text='Click for view date picker',reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(callback_data='ready',text='Click')]]))awaitctx.state_manager.set(chat_id=ctx.chat_id,key='message_id',value=str(message.message_id))@staticmethodasyncdefclb_ready(ctx:Context):_,message_id,nav=awaitgather(ctx.api.answer_callback_query(ctx.update.callback_query.id),ctx.state_manager.get(chat_id=ctx.chat_id,key='message_id'),Navigation.of(ctx))awaitnav.push(DatePicker.__name__,message_id=int(message_id))bot=Bot(token=TOKEN,root=RootWidget(children=[DatePicker()]))app=App()@app.on_event("startup")asyncdefstartup_event():asyncwithApi(TOKEN)asapi:awaitapi.set_webhook(WEBHOOK)@app.on_event("shutdown")asyncdefshutdown_event():asyncwithApi(TOKEN)asapi:awaitapi.delete_webhook()awaitbot.close_session()@app.post(f'/{TOKEN}')asyncdefindex(request:Request):awaitbot.handle(awaitrequest.json())return""
Package: telegram-cleaner
Telegram Cleaner ♻️Delete all your messages of any type.🇷🇺 RUSSIAN DISCLAIMER: Telegram не является анонимным и никогда им не был. Сотрудникам спецслужб известны телефонные номера около 30 миллионов пользователей Telegram из России, а равно и паспортные данных их владельцев. До 2020 года по телефону можно было найти любого пользователя. Чекистские подстилки массово скупали симки, вбивали в контакты тысячи случайных номеров, а потом сохраняли в базе связку id пользователя и номера телефона. Так собиралась пользовательская база, например, «Глаза Бога» 👁️. С учетом того, что Роскомнадзор запустил бота для поиска экстремистских комментариев в сети, в т.ч. в Telegram, я настоятельно рекомендую вам потереть свои старые комментарии в каналах и группах ДАЖЕ ЕСЛИ ВАС НЕТУ В БАЗАХ БОТОВ ДЛЯ ПРОБИВА. Помните, что Telegram сотрудничает с ФСБ и другими спецслужбами и сливает данные тех же террористов, наркоторговцев... и даже распространителей слухов в Индии. Если сотрудники телеги получат на вас запрос от гэбни, товесьма вероятноникто из них не удосужится выяснить, настоящий вы ли террорист или же это обычный спам запросами на неугодных режиму, они просто передадут ваши ip-адрес и номер телефона.⚠️ WARNING: before using this utility, you can save all your data using the desktop application:Settings>Advanced>Export Telegram data.Installation:# via pip$pipinstall-Utelegram-cleaner# via pipx$pipxinstalltelegram-cleanerUsage:# help$tg-clean-h# first save your chats because the data exported by telegram does not have information about group and user IDs$tg-cleandump_chats>mychats.json# you can extract data from this file using jq$jq-r'.[] | "\( .id ) \( .username  ) " +if has("title")then .titleelse "\( .first_name ) \( .last_name  )"end'mychats.json777000nullTelegramnull
-1001436354653nwsruNEWS.ru|Новости
...# delete messages in group chats, comments, posts$tg-clean-vvdelete_group_messages# delete private chats without confirmation$tg-clean-ydelete_private_chats# delete all your messages of any type in chats except those specified$tg-clean--keep-chats1234567890,1234567891,@durovsYou can use customAPI_IDandAPI_HASH(official apps). Add this lines to~/.bashrcor~/.zshrc:exportTG_API_ID=6exportTG_API_HASH=eb06d4abfb49dc3eeb1aeb98ae0f581eAlso you can use.envfile with zsh dotenv plugin.