I am trying to make a Telegram bot to find leads for the website and with titles (First inline keyboard).
When we start a bot there's an inline keyboard to ask for what to do, all other options apart from 8th (custom input) work fine.
The flow of bot is > inline input(=!8)> text input1 >output (working)
However, with selection 8, inline input ('8') > text input 0 > text input 1> output (here the program mistakes the text input 0 for text input 1 and gives output)
def button(update, context):
# Get the user's selection
query = update.callback_query
selection = query.data
context.user_data['selection'] = selection
print("selection is",selection,)
#update.callback_query.message.reply_text('Please enter all links of company websites separated by commas\n For Example:adidas.com, google.com ')
if selection == '8':
# Start a conversation to get custom persona
print("moved in the if block to execute 8th selection")
custom_persona(update, context)
else:
print("choice not 8, moving to input_handler()")
enter_websitedata(update,selection)
input_handler(update,context)
CUSTOM_PERSONA,SAVE_CUSTOM,WEBSITE_DATA=range(3)
def custom_persona(update,context):
update.callback_query.message.reply_text('Please enter custom persona titles separated by commas')
context.user_data['custom_persona']=update.message.text
context.user_data['state'] = CUSTOM_PERSONA
print("ended custom_persona....moving to save_custom_persona")
return SAVE_CUSTOM
def save_custom_persona(update, context):
context.user_data['state'] = SAVE_CUSTOM
print("entered save_custom_persona")
print("custom persona is set as:", context.user_data['custom_persona'])
update.message.reply_text("Custom persona set as: {}. ".format(context.user_data['custom_persona']))
try:
context.user_data['custom_persona']=context.user_data['custom_persona'].split(",")
except:
context.bot.send_message(chat_id=update.effective_chat.id, text="Please enter the input in correct format.")
enter_websitedata(update,'8')
return WEBSITE_DATA
def websitedata(update,context):
input_handler(update, context, context.user_data.get('custom_persona'))
return ConversationHandler.END
def enter_websitedata(update,selection):
if selection != '8':
update.callback_query.message.reply_text('Please enter all links of company websites separated by commas\n For Example:adidas.com, google.com ')
else:
update.message.reply_text('Please enter all links of company websites separated by commas\n For Example:adidas.com, google.com ')
def stop(update, context):
update.message.reply_text("Goodbye!")
threading.Thread(target=shutdown).start()
custom_persona_handler = ConversationHandler(
entry_points=[CallbackQueryHandler(button, pattern='^8$')],
#entry_points=[CommandHandler('start',start)],
states={
CUSTOM_PERSONA: [MessageHandler(Filters.text, custom_persona)],
SAVE_CUSTOM: [MessageHandler(Filters.text, save_custom_persona)],
WEBSITE_DATA: [MessageHandler(Filters.text, websitedata ,pass_user_data=True)]
},
fallbacks=[CommandHandler('cancel', stop)],
name='custom_persona_handler'
)
updater = Updater(TOKEN, use_context=True)
updater.dispatcher.add_handler(CommandHandler('start', start))
updater.dispatcher.add_handler(CommandHandler('stop', stop))
updater.dispatcher.add_handler(CallbackQueryHandler(button))
updater.dispatcher.add_handler(MessageHandler(Filters.text, input_handler))
updater.dispatcher.add_handler(custom_persona_handler)
updater.start_polling()
updater.idle()
I have tried multiple tweeks in the custom_persona, save_custom_persona and the button functions. But still the output of save_custom_persona won't show up
(print("custom persona is set as:", context.user_data['custom_persona'])
update.message.reply_text("Custom persona set as: {}. ".format(context.user_data['custom_persona'])))
Also,I'm getting this error:
line 109, in custom_persona
context.user_data['custom_persona']=update.message.text
AttributeError: 'NoneType' object has no attribute 'text'
Inputted'HR,Research' (Titles as custom persona) as the input , which should be saved in context.user_data['custom_persona] but instead goes to user_input.
The whole output of the 8th selection with input:
moved in the if block to execute 8th selection
No error handlers are registered, logging exception.
Traceback (most recent call last):
File "/Users/name/opt/anaconda3/lib/python3.9/site-packages/telegram/ext/dispatcher.py", line 557, in process_update
handler.handle_update(update, self, check, context)
File "/Users/name/opt/anaconda3/lib/python3.9/site-packages/telegram/ext/handler.py", line 199, in handle_update
return self.callback(update, context)
File "/Users/name/Desktop/python dev/python app/Outreach_tg_bot/tg_bot.py", line 50, in button
custom_persona(update, context)
File "/Users/name/Desktop/python dev/python app/Outreach_tg_bot/tg_bot.py", line 109, in custom_persona
context.user_data['custom_persona']=update.message.text
AttributeError: 'NoneType' object has no attribute 'text'
user input is hr,research
recieved user_input from enter_webistedata function hr,research
Printing the data input for now, which will be fed to execute() 8 <class 'str'> hr,research <class 'str'>
['hr', 'research'] now user input converted into a <class 'list'>
data: 8 ['hr', 'research']
processing search for 8 ['hr', 'research']
Executing search with Company_Name: ['hr', 'research'] Persona: None
Related
btcli query
Enter wallet name (default): my-wallet-name
Enter hotkey name (default): my-hotkey
Enter uids to query (All): 18
Note that my-wallet-name, my-hotkey where actually correct names. My wallet with one of my hotkeys. And I decided to query the UID 18.
But btcli is returning an error with no specific message
AttributeError: 'Dendrite' object has no attribute 'forward_text'
Exception ignored in: <function Dendrite.__del__ at 0x7f5655e3adc0>
Traceback (most recent call last):
File "/home/eduardo/repos/bittensor/venv/lib/python3.8/site-packages/bittensor/_dendrite/dendrite_impl.py", line 107, in __del__
bittensor.logging.success('Dendrite Deleted', sufix = '')
File "/home/eduardo/repos/bittensor/venv/lib/python3.8/site-packages/bittensor/_logging/__init__.py", line 341, in success
cls()
File "/home/eduardo/repos/bittensor/venv/lib/python3.8/site-packages/bittensor/_logging/__init__.py", line 73, in __new__
config = logging.config()
File "/home/eduardo/repos/bittensor/venv/lib/python3.8/site-packages/bittensor/_logging/__init__.py", line 127, in config
parser = argparse.ArgumentParser()
File "/usr/lib/python3.8/argparse.py", line 1672, in __init__
prog = _os.path.basename(_sys.argv[0])
TypeError: 'NoneType' object is not subscriptable
What does this means?
How can I query an UID correctly?
I have try to look for UIDs to query but the tool does not give me any.
I was expecting a semantic error or a way to look for a UID i can query but not a TypeError.
It appears that command is broken and should be removed.
I opened an issue for you here: https://github.com/opentensor/bittensor/issues/1085
You can use the python API like:
import bittensor
UID: int = 18
subtensor = bittensor.subtensor( network="nakamoto" )
forward_text = "testing out querying the network"
wallet = bittensor.wallet( name = "my-wallet-name", hotkey = "my-hotkey" )
dend = bittensor.dendrite( wallet = wallet )
neuron = subtensor.neuron_for_uid( UID )
endpoint = bittensor.endpoint.from_neuron( neuron )
response_codes, times, query_responses = dend.generate(endpoint, forward_text, num_to_generate=64)
response_code_text = response_codes[0]
query_response = query_responses[0]
Hi there so I wanted to make a spotify voice assistant so I found a video on youtube and the guy just went through his code and how it works and left the source code on his github so I used that and configured it to work on my settings but i'm getting an attribute error enter with one of his lines and theres 3 files "main.py" "setup.txt" and "pepper.py" but the problem is in main so im gonna drop the code down below
main.py:
import pandas as pd
from speech_recognition import Microphone, Recognizer, UnknownValueError
import spotipy as sp
from spotipy.oauth2 import SpotifyOAuth
from pepper import *
# Set variables from setup.txt
setup = pd.read_csv(r'C:\Users\Yousif\Documents\Python spotify\setup.txt', sep='=', index_col=0, squeeze=True, header=None)
client_id = setup['client_id']
client_secret = setup['client_secret']
device_name = setup['device_name']
redirect_uri = setup['redirect_uri']
scope = setup['scope']
username = setup['username']
# Connecting to the Spotify account
auth_manager = SpotifyOAuth(
client_id=client_id,
client_secret=client_secret,
redirect_uri=redirect_uri,
scope=scope,
username=username)
spotify = sp.Spotify(auth_manager=auth_manager)
# Selecting device to play from
devices = spotify.devices()
deviceID = None
for d in devices['devices']:
d['name'] = d['name'].replace('’', '\'')
if d['name'] == device_name:
deviceID = d['id']
break
# Setup microphone and speech recognizer
r = Recognizer()
m = None
input_mic = 'Voicemod Virtual Audio Device (WDM)' # Use whatever is your desired input
for i, microphone_name in enumerate(Microphone.list_microphone_names()):
if microphone_name == input_mic:
m = Microphone(device_index=i)
while True:
"""
Commands will be entered in the specific format explained here:
- the first word will be one of: 'album', 'artist', 'play'
- then the name of whatever item is wanted
"""
with m as source:
r.adjust_for_ambient_noise(source=source)
audio = r.listen(source=source)
command = None
try:
command = r.recognize_google(audio_data=audio).lower()
except UnknownValueError:
continue
print(command)
words = command.split()
if len(words) <= 1:
print('Could not understand. Try again')
continue
name = ' '.join(words[1:])
try:
if words[0] == 'album':
uri = get_album_uri(spotify=spotify, name=name)
play_album(spotify=spotify, device_id=deviceID, uri=uri)
elif words[0] == 'artist':
uri = get_artist_uri(spotify=spotify, name=name)
play_artist(spotify=spotify, device_id=deviceID, uri=uri)
elif words[0] == 'play':
uri = get_track_uri(spotify=spotify, name=name)
play_track(spotify=spotify, device_id=deviceID, uri=uri)
else:
print('Specify either "album", "artist" or "play". Try Again')
except InvalidSearchError:
print('InvalidSearchError. Try Again')
the exact error is:
Traceback (most recent call last):
File "c:/Users/Yousif/Documents/Python spotify/main.py", line 49, in <module>
with m as source:
AttributeError: __enter__
__enter__ is a python method that allows you to implement objects that can be used easily with the with statement. A useful example could be a database connection object (which then automagically closes the connection once the corresponding 'with'-statement goes out of scope):
class DatabaseConnection(object):
def __enter__(self):
# make a database connection and return it
...
return self.dbconn
def __exit__(self, exc_type, exc_val, exc_tb):
# make sure the dbconnection gets closed
self.dbconn.close()
...
The error here is caused because m = None, and None cannot be used in a with statement.
>>> with None as a:
... print(a)
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: __enter__
I'm trying to access data for an individual ride using the Strava API but when I add the ride ID I get an error. Essentially I'd like to be able to access things like distance and times and see this as the first step but I can't pull back much information on a single ride. Here is the code and error:
from stravalib.client import Client
client = Client(access_token='My token here')
athlete = client.get_athlete() # Get John's full athlete record
print("Hello, {}. I know your email is {}".format(athlete.firstname, athlete.email))
# "Hello, John. I know your email is john#example.com"
activities = client.get_activities(limit=10)
assert len(list(activities)) == 10
#View activities
for x in activities:
print (x)
#<Activity id=270828720 name='Evening Ride' resource_state=2>
#<Activity id=270590277 name='Morning Ride' resource_state=2>
#<Activity id=270577804 name='Evening Ride' resource_state=2>
#<Activity id=270137878 name='Morning Ride' resource_state=2>
a = client.get_activity(270137878)
#Traceback (most recent call last):
# File "<ipython-input-22-a7e56786804d>", line 1, in <module>
# a = client.get_activity(270137878)
# File "C:\Anaconda3\lib\site-packages\stravalib\client.py", line 423, in get_activity
# return model.Activity.deserialize(raw, bind_client=self)
# File "C:\Anaconda3\lib\site-packages\stravalib\model.py", line 106, in deserialize
# o.from_dict(v)
# File "C:\Anaconda3\lib\site-packages\stravalib\model.py", line 41, in from_dict
# raise AttributeError("Error setting attribute {0} on entity {1}, value: {2!r}".format(k, self, v))
#AttributeError: Error setting attribute photos on entity <Activity id=270137878 name=None resource_state=3>, value: {'primary': None, 'count': 0}
Did you get an answer to this? The issue was a change to the Strava API V3 which added photos, and stravalib hadnt been updated to reflect this -
https://github.com/hozn/stravalib/issues/45
Its been fixed now
I'm trying to make it so that when a user enters their name, password, etc, it stores it globally so that the program is able to connect with that name. I've defined the variables at top like this:
global server
server = ""
global nick
nick = ""
global altnick
altnick = ""
global password
password = ""
global channel
channel = ""
Then, when the Tkinter program comes in, the user can use the Entries to enter all the proper values:
networktop = Toplevel(master=root)
networktop.title("Network List")
networktop.geometry("300x220")
Label(networktop, text="Nickname:").pack()
nickbox = Entry(networktop)
nickbox.grid(column="50", row="50")
nickbox.pack()
nick = nickbox.get()
Label(networktop, text="Alternate nick:").pack()
altbox = Entry(networktop)
altbox.grid(column="50", row="50")
altbox.pack()
altnick = altbox.get()
Label(networktop, text="Password:").pack()
pwbox = Entry(networktop, show="*")
pwbox.grid(column="50", row="50")
pwbox.pack()
password = pwbox.get()
Label(networktop, text="Channel to join:").pack()
chanbox = Entry(networktop)
chanbox.grid(column="50", row="50")
chanbox.pack()
channel = chanbox.get()
listvar = StringVar(networktop)
listvar.set("Choose a network...") # default value
listnetwork = OptionMenu(networktop, listvar, "irc.freenode.net")
listnetwork.config(width="50")
listnetwork.grid(column="50", row="50")
listnetwork.pack()
server = listvar.get()
networkconnect = Button(networktop, text="Connect", command=connect)
networkcancel = Button(networktop, text="Cancel", command=networktop.destroy)
networkcancel.pack(side=LEFT)
networkconnect.pack(side=RIGHT)
What I'm trying to achieve here is that when something is entered in (e.g. "NickName") it replaces nick = "" at top with nick = "NickName", so that when "Connect" is pressed it would connect to the server with "NickName". But I get the following error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1470, in __call__
return self.func(*args)
File "C:\Users\dell\Desktop\irchat.py", line 29, in connect
irc.connect((server, 6667))
File "C:\Python27\lib\socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
error: [Errno 10049] The requested address is not valid in its context
I feel like I'm being a total noob here and the solution is probably easy as pie. xD
It appears you are getting the value of the entry widget before the user has an opportunity to enter any text. You're creating the widget and then immediately getting the value. Because of this, server is the empty string and thus the socket code is failing.
You don't want to get the value until the user has click the Connect button.
For my IRC bot when I try to use the `db addcol command I will get that Index error but I got no idea what is wrong with it.
#hook.command(adminonly=True, autohelp=False)
def db(inp,db=None):
split = inp.split(' ')
action = split[0]
if "init" in action:
result = db.execute("create table if not exists users(nick primary key, host, location, greeting, lastfm, fines, battlestation, desktop, horoscope, version)")
db.commit()
return result
elif "addcol" in action:
table = split[1]
col = split[2]
if table is not None and col is not None:
db.execute("ALTER TABLE {} ADD COLUMN {}".format(table,col))
db.commit
return "Added Column"
That is the command I am trying to execute and here is the error:
Unhandled exeption in thread started by <function run at 0xb70d6844
Traceback (most recent call last):
File "core/main.py", line 68, in run
out = func(input.inp, **kw)
File "plugins/core_admin_global.py", :ine 308, in db
col = split[2]
IndexError: list index out of range
You will find the whole code at my GIT repository.
Edit: This bot is just a little thing I have been playing around with while learning python so don't expect me to be too knowledgeable about this.
Yet another edit:
The command I am trying to add, just replace desktop with mom.
#hook.command(autohelp=False)
def desktop(inp, nick=None, conn=None, chan=None,db=None, notice=None):
"desktop http://url.to/desktop | # nick -- Shows a users Desktop."
if inp:
if "http" in inp:
database.set(db,'users','desktop',inp.strip(),'nick',nick)
notice("Saved your desktop.")
return
elif 'del' in inp:
database.set(db,'users','desktop','','nick',nick)
notice("Deleted your desktop.")
return
else:
if '#' in inp: nick = inp.split('#')[1].strip()
else: nick = inp.strip()
result = database.get(db,'users','desktop','nick',nick)
if result:
return '{}: {}'.format(nick,result)
else:
if not '#' in inp: notice(desktop.__doc__)
return 'No desktop saved for {}.'.format(nick)