Telegram bot polling function - bots

This is my first time trying to make a telegram bot.
Code:
import os
import telebot
API_TOKEN = os.getenv('API_KEY')
bot = telebot.TeleBot(API_TOKEN)
#bot.message_handler(commands=['hello'])
def send_welcome(message):
bot.reply_to(message, "HI!")
bot.polling()
Error:
Traceback (most recent call last):
File "/Users/anshtyagi/Documents/telegram bot/main.py", line 23, in <module>
bot.polling()
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/telebot/__init__.py", line 621, in polling
self.__threaded_polling(non_stop=non_stop, interval=interval, timeout=timeout, long_polling_timeout=long_polling_timeout,
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/telebot/__init__.py", line 695, in __threaded_polling
raise e
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/telebot/__init__.py", line 650, in __threaded_polling
polling_thread.raise_exceptions()
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/telebot/util.py", line 111, in raise_exceptions
raise self.exception_info
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/telebot/util.py", line 93, in run
task(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/telebot/__init__.py", line 360, in __retrieve_updates
updates = self.get_updates(offset=(self.last_update_id + 1),
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/telebot/__init__.py", line 338, in get_updates
json_updates = apihelper.get_updates(self.token, offset, limit, timeout, allowed_updates, long_polling_timeout)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/telebot/apihelper.py", line 324, in get_updates
return _make_request(token, method_url, params=payload)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/telebot/apihelper.py", line 80, in _make_request
raise Exception('Bot token is not defined')
Exception: Bot token is not defined
I am getting this error while running my telegram bot this is my first time. I have seen some tutorials how to make a bot but mine is not working. I have posted my token in .env file and imported it using os.getenv. I am just simply trying to make a simple bot just for my knowledge as I have tried making discord bots and it was great experience and I learned many new languages so I thought why not try this also.

I'm also new to python and telegram bots, but my first bot is running ok and I see the problem in your code. Your exception tells us Exception: Bot token is not defined. So your script doesn't get a token from the system var.
You say that you have your token in .env file. To get os variable from that file first of all we must import a module: from dotenv import load_dotenv.
Next we must import variables from that file using the function load_dotenv().
After that we can read our variables with os.getenv. So that line of your code seems to be correct. If there is no variable in the file os.getenv should get it from the os.
So your code may look like:
import os
import telebot
from dotenv import load_dotenv
load_dotenv()
API_TOKEN = os.getenv('API_KEY')
bot = telebot.TeleBot(API_TOKEN)
#bot.message_handler(commands=['hello'])
def send_welcome(message):
bot.reply_to(message, "HI!")
bot.polling()

try this:
import telebot
bot = telebot.TeleBot("API_KEY")
instead of:
import os
import telebot
API_TOKEN = os.getenv('API_KEY')
bot = telebot.TeleBot(API_TOKEN)

Related

I built a telegram bot but it doesn't work

Hello everyone please I was working on a telegram bot, this bot works fine on my local pc but when I upload the file to my VPS it gives errors.
This a photo of it working on my local PC Photo Link
And here's the code also
from telegram.ext import Updater,CommandHandler
def start(update,context) -> None:
message = update.message
context.bot.send_message(message.chat.id,"hi",parse_mode="markdown")
def main():
updater = Updater("5412956496:AAFkQCS-mKcqUm1PeRV3U8pjqGrN0k1KpI4",use_context=True)
print("Started")
updater.dispatcher.add_handler(CommandHandler('start', start))
updater.start_polling()
if _name_ == "_main_":
main()
But on my VPS it gives me this error
File "app.py", line 2, in <module>
from telegram.ext import Updater,CommandHandler
File "/usr/local/lib/python3.6/dist-packages/telegram/ext/__init__.py", line 31, in <module>
from .updater import Updater
File "/usr/local/lib/python3.6/dist-packages/telegram/ext/updater.py", line 55, in <module>
class Updater(Generic[CCT, UD, CD, BD]):
File "/usr/local/lib/python3.6/dist-packages/telegram/ext/updater.py", line 198, in Updater
dispatcher: Dispatcher[CCT, UD, CD, BD] = None,
File "/usr/lib/python3.6/typing.py", line 682, in inner
return func(*args, **kwds)
File "/usr/lib/python3.6/typing.py", line 1143, in getitem
orig_bases=self.orig_bases)
File "/usr/lib/python3.6/typing.py", line 978, in new
self = super().new(cls, name, bases, namespace, _root=True)
File "/usr/lib/python3.6/typing.py", line 137, in new
return super().new(cls, name, bases, namespace)
File "/usr/lib/python3.6/abc.py", line 133, in new
cls = super().new(mcls, name, bases, namespace, **kwargs)
TypeError: dict slot disallowed: we already got one
I really would appreciate help offered thank you.
You should revoke the bot token that you posted.
Which version of python-telegram-bot are you using? v13.12+ does not support python 3.6.
Disclaimer: I'm currently the maintainer of python-telegram-bot.

How to run Python scripts on Azure?

I am trying to run some Python code in Azure, for the first time ever. I Googled 'how to run Python scripts in Azure' and came across the following link.
https://learn.microsoft.com/en-us/azure/automation/learn/automation-tutorial-runbook-textual-python-3
Essentially, I need to do this.
Open the textual editor by selecting Edit on the MyFirstRunbook-Python3 pane.
Add the following code to authenticate to Azure:
import os
from azure.mgmt.compute import ComputeManagementClient
import azure.mgmt.resource
import automationassets
def get_automation_runas_credential(runas_connection):
from OpenSSL import crypto
import binascii
from msrestazure import azure_active_directory
import adal
# Get the Azure Automation RunAs service principal certificate
cert = automationassets.get_automation_certificate("AzureRunAsCertificate")
pks12_cert = crypto.load_pkcs12(cert)
pem_pkey = crypto.dump_privatekey(crypto.FILETYPE_PEM,pks12_cert.get_privatekey())
# Get run as connection information for the Azure Automation service principal
application_id = runas_connection["ApplicationId"]
thumbprint = runas_connection["CertificateThumbprint"]
tenant_id = runas_connection["TenantId"]
# Authenticate with service principal certificate
resource ="https://management.core.windows.net/"
authority_url = ("https://login.microsoftonline.com/"+tenant_id)
context = adal.AuthenticationContext(authority_url)
return azure_active_directory.AdalAuthentication(
lambda: context.acquire_token_with_client_certificate(
resource,
application_id,
pem_pkey,
thumbprint)
)
# Authenticate to Azure using the Azure Automation RunAs service principal
runas_connection = automationassets.get_automation_connection("AzureRunAsConnection")
azure_credential = get_automation_runas_credential(runas_connection)
When I run that code, I get this error.
Failed
Traceback (most recent call last): File "C:\WPy64-3800\python-3.8.0.amd64\lib\automationassets.py", line 155, in _issue_request response = urllib.request.urlopen(request) File "C:\WPy64-3800\python-3.8.0.amd64\lib\urllib\request.py", line 222, in urlopen return opener.open(url, data, timeout) File "C:\WPy64-3800\python-3.8.0.amd64\lib\urllib\request.py", line 531, in open response = meth(req, response) File "C:\WPy64-3800\python-3.8.0.amd64\lib\urllib\request.py", line 640, in http_response response = self.parent.error( File "C:\WPy64-3800\python-3.8.0.amd64\lib\urllib\request.py", line 569, in error return self._call_chain(*args) File "C:\WPy64-3800\python-3.8.0.amd64\lib\urllib\request.py", line 502, in _call_chain result = func(*args) File "C:\WPy64-3800\python-3.8.0.amd64\lib\urllib\request.py", line 649, in http_error_default raise HTTPError(req.full_url, code, msg, hdrs, fp)urllib.error.HTTPError: HTTP Error 404: Not FoundDuring handling of the above exception, another exception occurred:Traceback (most recent call last): File "C:\Temp\nmcijfgi.bro\a761c289-67d9-493a-99b2-3ba7d46a7cd9", line 36, in <module> runas_connection = automationassets.get_automation_connection("AzureRunAsConnection") File "C:\WPy64-3800\python-3.8.0.amd64\lib\automationassets.py", line 232, in get_automation_connection connection = _client.get_connection_asset(name) File "C:\WPy64-3800\python-3.8.0.amd64\lib\automationassets.py", line 187, in get_connection_asset return self._issue_request(url, method=self._GET) File "C:\WPy64-3800\python-3.8.0.amd64\lib\automationassets.py", line 158, in _issue_request raise AutomationAssetNotFound()automationassets.AutomationAssetNotFound
Do I need 'cert', 'pks12_cert', or 'pem_pkey'? I don't think I have those. I'm not even sure what those things are. Again, I am trying to setup my Azure environment to run a Python script, which works totally fine on my desktop (Spyder).
Most likely you haven't created an Azure Run As Account. Follow the steps here to do so.

How to use Microsoft Online Exchange with python to send mail

I want to send an Email from my outlook account using Python. I used the below code running in an AWS EC2 instance to generate an email.
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
server = smtplib.SMTP('smtp.office365.com', 587)
server.starttls()
server.login("<outlook_mail_id>","<outlook_password>")
server.sendmail("<outlook_mail_id>", "<recipient_email_id> ", "Test Message")
server.quit()
But while running this I get the below error
Traceback (most recent call last):
File "smtp_office_365.py", line 12, in <module>
server.login("<outlook_email_id>","<outlook_pass>")
File "/usr/local/lib/python3.8/smtplib.py", line 734, in login
raise last_exception
File "/usr/local/lib/python3.8/smtplib.py", line 723, in login
(code, resp) = self.auth(
File "/usr/local/lib/python3.8/smtplib.py", line 646, in auth
raise SMTPAuthenticationError(code, resp)
smtplib.SMTPAuthenticationError: (535, b'5.7.3 Authentication unsuccessful [MN2PR15CA0001.namprd15.prod.outlook.com]')
I am able to login into web outlook account using these credentials. Hence to check further I connected with my Admin team and they said that Basic Authentication is disabled for this account and can't be enabled in any case. They suggested me to use modern Authentication method by using Microsoft Online Exchange.
On further exploration I found the below script to send the mail
from exchangelib import DELEGATE, IMPERSONATION, Account, Credentials, Configuration
credentials = Credentials('<outlook_mail_id>', '<outlook_password>')
account = Account('<outlook_mail_id>', credentials=credentials, autodiscover=True)
for item in account.inbox.all().order_by('-datetime_received')[:100]:
print(item.subject, item.sender, item.datetime_received)
But I get the below error while running the script
Traceback (most recent call last):
File "test_exchange.py", line 5, in <module>
account = Account('<outlook_email_id>', credentials=credentials, autodiscover=True)
File "/home/ec2-user/.local/lib/python3.8/site-packages/exchangelib/account.py", line 116, in __init__
self.ad_response, self.protocol = discover(
File "/home/ec2-user/.local/lib/python3.8/site-packages/exchangelib/autodiscover/discovery.py", line 24, in discover
return Autodiscovery(
File "/home/ec2-user/.local/lib/python3.8/site-packages/exchangelib/autodiscover/discovery.py", line 123, in discover
ad_response = self._step_1(hostname=domain)
File "/home/ec2-user/.local/lib/python3.8/site-packages/exchangelib/autodiscover/discovery.py", line 433, in _step_1
return self._step_2(hostname=hostname)
File "/home/ec2-user/.local/lib/python3.8/site-packages/exchangelib/autodiscover/discovery.py", line 451, in _step_2
return self._step_3(hostname=hostname)
File "/home/ec2-user/.local/lib/python3.8/site-packages/exchangelib/autodiscover/discovery.py", line 483, in _step_3
return self._step_4(hostname=hostname)
File "/home/ec2-user/.local/lib/python3.8/site-packages/exchangelib/autodiscover/discovery.py", line 514, in _step_4
return self._step_6()
File "/home/ec2-user/.local/lib/python3.8/site-packages/exchangelib/autodiscover/discovery.py", line 572, in _step_6
raise AutoDiscoverFailed(
exchangelib.errors.AutoDiscoverFailed: All steps in the autodiscover protocol failed for email '<outlook_email_id>'. If you think this is an error, consider doing an official test at https://testconnectivity.microsoft.com
Please let me know if more details are required. Any help would be appreciated.
Thanks

Unable to log a cog, gettin ExtensionNotFound

I'm not sure if I'm missing something here, but I have a .py file in my cogs folder that will not load. Keeps giving me error ```The above exception was the direct cause of the following exception:
discord.ext.commands.errors.ExtensionNotFound: Extension 'cogs.determineHit' could not be loaded.
The following is a picture of my file locations:
https://imgur.com/a/gBbX4lM
I will copy the code here as well for you to see, but will snip the bulk of the code as it is quite long. If you need further information, please let me know.
import discord
import json
import random
import os
import time
from pathlib import Path
from threading import Timer
from discord.ext import commands
# from Roll_not_strike import *
# from Roll_true_strike import *
# from playerone_zero_current_hp import *
# from playertwo_zero_current_hp import *
def evasionTimer(self):
pass
class Hit(commands.Cog):
def __init__(self, client):
self.client = client
# Bulk of Code
def setup(client):
client.add_cog(Hit(client))
With the main script of the bot being:
import discord
import os
from discord.ext import commands
token = open("token.txt", "r").read()
client = commands.Bot(command_prefix = '!')
#client.command()
async def load(ctx, extension):
client.load_extension("cogs." + extension)
#client.command()
async def unload(ctx, extension):
client.unload_extension("cogs." + extension)
for filename in os.listdir("./cogs"):
if filename.endswith('.py'):
client.load_extension("cogs." + filename[:-3])
client.run(token)
Every other cog in the cogs folder loads up just fine, should I remove determineHit.py I am not sure what I'm missing here. Any help would be appreciated.
Edit:
Before the request for a trace back was asked for, I started thinking on what was going on, and came to the conclusion that the file determineHit.py doesn't really use any discord commands. What is happening is user types in command to discord !roll, bot see that !roll command points to a method in determineHit.py where all the calculations are done (The code in that file is pure python, nothing calling upon discord commands), and then returns that data back to the bot, with all data that needs to be sent to the chat stored in a dictonary called msgwhich then has a for loop to print out all necessary information.
Example, in determineHit.py, you might find:
msg = []
msg.append("Hi Peoples!")
msg.append("Wow! You hit someone!")
msg.append("Aww! You missed!")
msg.append("These are Examples!)
return msg
back in the bot itself, it would unpack msg and print out the statements stored within with a for loop:
for msg_item in msg:
await ctx.send(msg_item)
Long story short, I assumed that because determineHit.py isn't using anything from the discord library, it doesn't need to be a cog, it can be in another folder in the same directory.
So I did this:
https://imgur.com/a/qM7v8E4
Hoping that might solve my problem. (The other files under determineHit.py are the same, they are just python files containing calculations and the like, they call on no methods in any discord library.)
Evidently, I am wrong. As when I try to run the bot with from determineHit import * I get the extension error that started this all. Run it without the above, and bot starts, but obviously can't run the command, because the method it calls on doesn't exist, because it can't see determineHit.py
Probably more wordy than you needed, I'm sorry. But anyway...
I also did the traceback someone reqested, and I got the following:
"C:\Users\arrae\PycharmProjects\Python Learning\venv\Scripts\python.exe" C:/Users/arrae/PycharmProjects/DiscordDiceGame/BotCommands.py
'Bot' object has no attribute 'load_extensions'
'Bot' object has no attribute 'load_extensions'
'Bot' object has no attribute 'load_extensions'
'Bot' object has no attribute 'load_extensions'
'Bot' object has no attribute 'load_extensions'
Bot is Online
mind you that this was done after I moved determineHit.py out of cogs, and put it in 'gamelogic' folder.
However, if it does help, I put determineHit.py back in the cogs folder, and ran the same traceback code offered:
"C:\Users\arrae\PycharmProjects\Python Learning\venv\Scripts\python.exe" C:/Users/arrae/PycharmProjects/DiscordDiceGame/BotCommands.py
Traceback (most recent call last):
File "C:\Users\arrae\PycharmProjects\Python Learning\venv\lib\site-packages\discord\ext\commands\bot.py", line 621, in load_extension
lib = importlib.import_module(name)
File "C:\Users\arrae\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users\arrae\PycharmProjects\DiscordDiceGame\cogs\determineHit.py", line 10, in <module>
from Roll_not_strike import *
ModuleNotFoundError: No module named 'Roll_not_strike'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:/Users/arrae/PycharmProjects/DiscordDiceGame/BotCommands.py", line 25, in <module>
client.load_extension("cogs." + filename[:-3])
File "C:\Users\arrae\PycharmProjects\Python Learning\venv\lib\site-packages\discord\ext\commands\bot.py", line 623, in load_extension
raise errors.ExtensionNotFound(name, e) from e
discord.ext.commands.errors.ExtensionNotFound: Extension 'cogs.determineHit' could not be loaded.
I'm sorry if I just made things more complicated. Thought I had found my own answer.
I would like to see an actual traceback.
You can create a dictionary, list each cog and see if it helps.
async def on_ready():
print('Bot is ready')
initial_extensions = (
'cogs.charCreation',
'cogs.charFeats',
'cogs.charSheet',
'cogs.gameCombat',
'cogs.determineHit'
)
for extension in initial_extensions:
try:
client.load_extensions(extension)
except Exception as e:
print(e)
Source: https://github.com/Rapptz/RoboDanny/blob/rewrite/bot.py
Edit: You need to place code above right to the main file after
client = commands.Bot(command_prefix = '!')
Put determineHit.py back to folder with cogs.
Right after
import discord
import os
from discord.ext import commands
paste the following lines to the main file
from gamelogic import onPRIUTil, playerone_zero_current_hp, playertwo_zero_current_hp, Roll_not_strike, Roll_true_strike

Posting Tweet Twython 3.1.0 and Python 3.3.2 on OSX

I am new to Python, and thought learning with Twitter would be useful to me.
I put the following code together via researching code on the internet.
import sys
from twython import Twython
CONSUMER_KEY = "xxxx"
CONSUMER_SECRET = "xxxx"
ACCESS_TOKEN = "xxxx"
ACCESS_TOKEN_SECRET = "xxxx"
twitter = Twython(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SEC$
twitter.update_status(status=sys.argv[1])
When I go to run the code I get errors, can anyone help? the errors are below:
$ python3 Twitter_Test_Put.py Test From Python
Traceback (most recent call last):
File "Twitter_Test_Put.py", line 12, in <module>
twitter.update_status(status=sys.argv[1])
File "/usr/local/Cellar/python3/3.3.2/Frameworks/Python.framework/Versions/3.3/lib/python3.3/sit e-packages/twython-3.1.0-py3.3.egg/twython/endpoints.py", line 90, in update_status
File "/usr/local/Cellar/python3/3.3.2/Frameworks/Python.framework/Versions/3.3/lib/python3.3/sit e-packages/twython-3.1.0-py3.3.egg/twython/api.py", line 234, in post
File "/usr/local/Cellar/python3/3.3.2/Frameworks/Python.framework/Versions/3.3/lib/python3.3/sit e-packages/twython-3.1.0-py3.3.egg/twython/api.py", line 224, in request
File "/usr/local/Cellar/python3/3.3.2/Frameworks/Python.framework/Versions/3.3/lib/python3.3/sit e-packages/twython-3.1.0-py3.3.egg/twython/api.py", line 194, in _request
twython.exceptions.TwythonAuthError: Twitter API returned a 401 (Unauthorized), An error occurred processing your request.
Any help will be much appreciated, I am a new to all of this so easy steps to follow will be great thank you in advance.

Resources