My code:
elif message.content.startswith(";random-number"):
channel = client.get_channel(1004728545911787740)
await channel.send("**Command received:** " + str(message.content) + "\n ```" + str(message) + "```")
try:
range = int(message.content.replace(";random-number ", "")
await message.channel.send("Random number: " + random.randint(0, int(range)))
except:
await message.channel.send(random.choice(["Use the command like this: ", "Here is how you can use the command: "]))
await message.channel.send("`;random-number [max number]`\nExample:\nUser - `;random-number 100`\nCorion - Random number: 67")
When I run my code I get this error:
File "main.py", line 150
await message.channel.send("Random number: " + random.randint(0, int(range)))
^
SyntaxError: invalid syntax
It seems there a syntax problem at this line:
I can't really understand where the syntax error is though. I also tried str-ing the random.randint(0,int(range) but it doesn't work either. Any help is appreciated!
Your syntax issue is the line above
range = int(message.content.replace(";random-number ", "")
You are missing the closing brace
range = int(message.content.replace(";random-number ", ""))
Related
I am creating a simple USPS Tracking Bot for Discord.
It works by using the !usps TRACKING NUMBER command in Discord
Here is the code:
import shippo
import discord
import asyncio
import datetime
token = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
client = discord.Client()
shippo.config.api_key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
#client.event
async def on_ready():
print('-------------------------')
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('-------------------------')
#client.event
async def on_message(message):
if message.author.bot:
return
if message.content.startswith('!help'):
embed = discord.Embed(title="Help", description="Use `!uSps TRACKING NUMBER` to get started!", color=0x8B4513)
embed.set_author(name="USPS Tracking", url="https://www.usps.com/", icon_url="https://www.freepnglogos.com/uploads/usps-png-logo/bridgeport-apartments-usps-png-logo-2.png")
embed.set_thumbnail(url="https://www.freepnglogos.com/uploads/usps-png-logo/bridgeport-apartments-usps-png-logo-2.png")
await message.channel.send(embed=embed)
if message.content.startswith('!'):
cmd = message.content.split()[0].lower()[1:]
args = message.content.split()[1:]
packageTrack = ' '.join(args)
tracking_number = packageTrack
carrier_token = 'usps'
tracking = shippo.Track.get_status(carrier_token, tracking_number)
d1 = datetime.datetime.strptime(tracking['tracking_status']['status_date'], "%Y-%m-%dT%H:%M:%SZ")
new_format = "%m-%d-%Y" + " at " + "%H:%M"
uspsStatus = tracking['tracking_status']['status_details'] + " - " + tracking['tracking_status']['status']
uspsCity = tracking['tracking_status']['location']['city']
uspsState = tracking['tracking_status']['location']['state']
uspsZip = tracking['tracking_status']['location']['zip']
uspsDate = d1.strftime(new_format)
if uspsCity is None:
print("Unavailable")
elif uspsZip is None:
print("Unavailable")
elif uspsState is None:
print("Unavailable")
if cmd == 'usps':
embed = discord.Embed(title="Tracking", color=0x8B4513)
embed.set_author(name="USPS Tracking", url="https://tools.usps.com/go/TrackConfirmAction?tLabels={}".format(str(tracking_number)), icon_url="https://www.freepnglogos.com/uploads/usps-png-logo/bridgeport-apartments-usps-png-logo-2.png")
embed.set_thumbnail(url="https://www.freepnglogos.com/uploads/usps-png-logo/bridgeport-apartments-usps-png-logo-2.png")
embed.add_field(name="Tracking Number: ", value="{}".format(str(tracking_number)), inline=False)
embed.add_field(name="Status: ", value="{}".format(str(uspsStatus)), inline=False)
embed.add_field(name="Date & Time: ", value="{}".format(str(uspsDate)), inline=False)
embed.add_field(name="Location: ", value="{}".format(str(uspsCity) + ", " + str(uspsState) + " " + str(uspsZip)), inline=False)
await message.channel.send(embed=embed)
client.run(token)
On Line 40 the uspsCity = tracking['tracking_status']['location']['city'] I get the TypeError: 'NoneType' object is not subscriptable error. As you can see I attempted to solve it in the way I thought would work, but it still writes the error. Lists and dicts are still slightly confusing to me so that could be why I'm not getting it.
This Error means you tried to get the elements of nothing (None).
tracking = shippo.Track.get_status(carrier_token, tracking_number)
I guess this function returned None. To avoid this add for example an if statement (try/catch is also possible):
if tracking not None:
uspsStatus = tracking['tracking_status']['status_details'] + " - " + tracking['tracking_status']['status']
uspsCity = tracking['tracking_status']['location']['city']
uspsState = tracking['tracking_status']['location']['state']
uspsZip = tracking['tracking_status']['location']['zip']
I have 3 lat/lngs and a URL that I am constructing. My output should be 3 URLs, for each lat/lng, I am receiving 6. What do I need to change in my code below to print 3 URLs instead of 6? The try block and first for loops start are error handling, if the script fails, try twice. I am getting 6 values even when the script does not fail.
def main():
for i in range(2):
for attempts in range (1):
try:
for lat, lon, id_, startDate, endDate in zip(latval, lonval, idVal, startDayValStr, endDayValStr):
time_param = '?start='+ startDate +'T'+ "01:00" + 'Z' + '&end='+ endDate + 'T' + "23:00" + 'Z'
hrPrecip = 'https://insight.api.wdtinc.com/hourly-precipitation/' + str(lat)+'/' + str(lon) + time_param + '&unit=inches'
print hrPrecip
except Exception as e:
attempts = i + 1
sleep(30)
print "now trying attempt #" + " " + str(attempts) + " " + "for error" " " + str(e)
print(traceback.format_exc())
logging.exception(e)
msg = "PYTHON ERRORS:\nTraceback info:\n" + traceback.format_exc()
logging.debug("sending error email")
emailserver.email_error_msg(msg)
if __name__ == "__main__":
main()
Output:
https://insight.api.wdtinc.com/hourly-precipitation/44.797207/-95.175648?start=2019-05-13T01:00Z&end=2019-05-13T23:00Z&unit=inches
https://insight.api.wdtinc.com/hourly-precipitation/44.796302/-95.180946?start=2019-05-13T01:00Z&end=2019-05-13T23:00Z&unit=inches
https://insight.api.wdtinc.com/hourly-precipitation/44.778728/-95.23022?start=2019-05-13T01:00Z&end=2019-05-13T23:00Z&unit=inches
https://insight.api.wdtinc.com/hourly-precipitation/44.797207/-95.175648?start=2019-05-13T01:00Z&end=2019-05-13T23:00Z&unit=inches
https://insight.api.wdtinc.com/hourly-precipitation/44.796302/-95.180946?start=2019-05-13T01:00Z&end=2019-05-13T23:00Z&unit=inches
https://insight.api.wdtinc.com/hourly-precipitation/44.778728/-95.23022?start=2019-05-13T01:00Z&end=2019-05-13T23:00Z&unit=inches`
It could be the try: and except: block. failing in the first. I am guessing you do not need the second loop with attempt in range(1). In fact you do not need any loop here.
I wrote a simple Python twitch bot following a video tutorial, but the tutorial didn't include whisper functionality. It can currently connect to the chat of the channel I specify, but when I try to have it send a whisper nothing happens. Here's the relevant code bits:
import socket
def openSocket():
s = socket.socket()
s.connect((HOST, PORT))
message = "PASS " + PASS + "\r\n"
s.send(message.encode('utf-8'))
message = "NICK " + USER + "\r\n"
s.send(message.encode('utf-8'))
message = "JOIN #" + CHAN + "\r\n"
s.send(message.encode('utf-8'))
return s
def sendMessage(s, message):
messageTemp = "PRIVMSG #" + CHAN + " :" + message + "\r\n"
s.send(messageTemp.encode('utf-8'))
print("Sent:" + messageTemp)
def sendWhisper(s, user, message):
messageTemp = "PRIVMSG #jtv :/w " + user + " " + message
s.send(messageTemp.encode('utf-8'))
import string
from Socket import sendMessage
def joinRoom(s):
readbuffer = ""
Loading = True
while Loading:
readbuffer = readbuffer + s.recv(1024).decode()
temp = readbuffer.split('\n')
readbuffer = temp.pop()
for line in temp:
print(line)
Loading = loadingComplete(line)
def loadingComplete(line):
if("End of /NAMES list" in line):
return False;
else: return True
I've been reading a little bit about connecting to some sort of group chat in order to make this work, but I'm confused and haven't found what I'm looking for. It seems like it should be an easy fix. Any help is appreciated.
You were very close. Where you messed up is there should not be a # in front of jtv:
def sendWhisper(s, user, message):
messageTemp = "PRIVMSG jtv :/w " + user + " " + message
s.send(messageTemp.encode('utf-8'))
Okay, so I've got a bit of Python IRC Bot code, and I recently added a weather command to it, but it doesn't seem to work... heres the code
# Import some necessary libraries.
import socket
import time
import httplib
def commands(nick,channel,message):
if message.find('!test')!=-1:
ircsock.send('PRIVMSG %s :%s: test complete\r\n' % (channel,nick))
elif message.find('!help')!=-1:
ircsock.send('PRIVMSG %s :%s: My other command is test.\r\n' % (channel,nick))
elif message.find('!sex')!=-1:
ircsock.send('PRIVMSG %s :%s: But why?\r\n' % (channel,nick))
elif message.find('!quit')!=-1:
ircsock.send('QUIT :For the bones of the weak shall support me\r\n')
die('Quit command given')
elif message.find('!op')!=-1:
ircsock.send('MODE %s +o :%s\n' % (channel,nick))
elif message.find('!deop')!=-1:
ircsock.send('MODE %s -o :%s\n' % (channel,nick))
elif message.find('!weather')!=-1:
tmp = message.find(':!weather')
city = tmp[1].strip()
reqest_str = '/laika_zinas/?city=' + city
c = httplib.HTTPConnection("www.1188.lv")
c.request("GET", reqest_str)
ra = c.getresponse()
datas = ra.read()
temp, wind = tpars(datas)
ircsock.send('PRIVMSG %s :%s: [+] Temp: '+ temp +' C | Wind: '+ wind +' m/s' % (channel,nick))
c.close()
# Some basic variables used to configure the bot
server = "n0cht.bawx.net" # Server
channel = "#python" # Channel
botnick = "PyleDrivr" # Your bots nick
def ping(ircmsg): # This is our first function! It will respond to server Pings.
ircsock.send("PONG "+ ircmsg +"\n")
print("Ping replied\n\r")
def sendmsg(chan , msg): # This is the send message function, it simply sends messages to the channel.
ircsock.send("PRIVMSG "+ chan +" :"+ msg +"\n")
def joinchan(chan): # This function is used to join channels.
ircsock.send("JOIN "+ chan +"\n")
ircsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ircsock.connect((server, 6667)) # Here we connect to the server using the port 6667
ircsock.send("USER "+ botnick +" "+ botnick +" "+ botnick +" :PyleDrivr\n") # user authentication
ircsock.send("NICK "+ botnick +"\n") # here we actually assign the nick to the bot
joinchan(channel) # Join the channel using the functions we previously defined
while 1: # Be careful with these! it might send you to an infinite loop
ircmsg = ircsock.recv(2048) # receive data from the server
ircmsg = ircmsg.strip('\n\r') # removing any unnecessary linebreaks.
print(ircmsg) # Here we print what's coming from the server
if ircmsg.find(' PRIVMSG ')!=-1:
nick=ircmsg.split('!')[0][1:]
channel=ircmsg.split(' PRIVMSG ')[-1].split(' :')[0]
commands(nick,channel,ircmsg)
if ircmsg.find("PING :") != -1: # if the server pings us then we've got to respond!
ping(ircmsg)
Now, when I run the bot, it works just fine, but then this happens when I issue the command:
<wh0r3[mint]> !weather 99654
* PyleDrivr has quit (Client exited)
And here's what the term shows:
:wh0r3[mint]!~wh0r3#n0cht-D1D272D.gci.net PRIVMSG #lobby :!weather 99654
Traceback (most recent call last):
File "pyledrivr.py", line 65, in <module>
commands(nick,channel,ircmsg)
File "pyledrivr.py", line 22, in commands
city = tmp[1].strip()
TypeError: 'int' object has no attribute '__getitem__'
I have no idea what this means or how to fix it. and ideas?
This line:
tmp = message.find(':!weather')
assigns an integer to tmp: the position at which the string ':!weather' was found in message (see find). It may not even be found at all, since you check in the line above that '!weather' is in message, not ':!weather'.
Then you try and access tmp[1]. But tmp is just a number; it doesn't have a [1].
If you want to get the substring of message that follows '!weather', you could do this:
city = message[message.find('!weather')+8:].strip()
(8 being the length of '!weather')
Or you might find it easier to use split:
city = message.split('!weather')[1].strip()
if data.find('!search') != -1:
nick = data.split('!')[ 0 ].replace(':','')
conn = httplib.HTTPConnection("www.md5.rednoize.com")
conn.request("GET", "?q=" + arg)
response = conn.getresponse()
data = response.read()
result = re.findall('<div id="result" >(.+?)</div', data)
if result:
sck.send('PRIVMSG ' + chan + result + '\r\n')
else:
sck.send('PRIVMSG ' + chan + " :" ' could not find the hash' + '\r\n')
When I run this code I get this error:
conn.request("GET " + "?q=" + arg)
TypeError: cannot concatenate 'str' and 'list' objects
How can I fix this?
Where does arg come from? Do you know what it's supposed to contain?
arg is apparently a list, not a string. Try replacing arg with str(arg[0]) and see if that works.