Mongo db won't connect with my code or write to the database - discord.py

This is my code and I'm trying to get it so when a user does the add command, it stores their id and number they have used the command, but this isn't working, please can someone help.
num = 0
#client.command()
async def add(ctx):
global num
num += 1
await ctx.send('non')
mongo_url = "mongodb+=true&w=majority"
cluster = MongoClient(mongo_url)
db = cluster["mongo_url "]
collection = db["mongo_url "]
ping_cm = {"bank":num}
collection.insert_one(ping_cm)

I assume your mongo_url token is incorrect, it should have your name and password and db that you are storing it to, but you are accessing your token currently instead of your bank name, whatever that is called,
for example,
db = cluster["mongo_url "] #This has been set to your token, your mongo_url which won't do anything
You have used "bank" in other parts of your code, which is really confusing but I assume thats what you want to do and access, this will then store it in different rows for each user id who uses the command
num = 0
#client.command()
async def add(ctx):
global num
num += 1
await ctx.send('non')
mongo_url = "YOUR_MONGO_DATABASE_URL"
cluster = MongoClient(mongo_url)
db = cluster["bank"]
collection = db["bank"]
ping_cm = {"bank":num}
collection.insert_one(ping_cm)
await ctx.channel.send("Bank Updated!")
Make sure you are providing your mongo url "properly" otherwise the code won't be working at all they should look like this: eg.
EXAMPLE ONLY
mongo_url = "mongodb+srv://name:password#bank.9999000.mongodb.net/bank?retryWrites=true&w=majority" #EXAMPLE
You can get the URL when you go to the database you want to connect to, the click manage > db_url and copy that where I have included “YOUR_MONGO_DATABASE_URL" that should work if it is correct

Related

How to rig a bot's command to only a certain user

I've been making this pp size machine, which is somewhat like dank memer's one
#client.command()
async def pp(ctx,member : discord.Member):
size=random.randint(1,10)
message = "8"
for x in range (size):
message= message + "="
if x == size-1:
message = message + "D"
if member == "PROTATO#6826":
message = "8D"
ppsize = discord.Embed(color=discord.Colour.orange(), title=f"PP size",description=f"""{member}'s penis
{message} """)
await ctx.send(embed = ppsize)
But i want to rig the command for a certain user to only show "8D" instead of the random lengths.
But no matter what it is the
if member == "PROTATO#6826":
message = "8D"
code doesnt run or gets over looked?
Can someone help me out with this?
You can check if the member mentioned has the same id as a specific user. You can either enable developer mode on discord, or you can print the member.id at the very beginning. Do view a code example below.
#client.command()
async def pp(ctx, member: discord.Member):
print(member.id) # this would print a user's unique id
message = "Hey!"
if member.id == 394506589350002688: # replace this id with what was printed at the start
message = "Hello!"
await ctx.send(message)
Similar Questions:
How to check if message was sent by certain user? - SO
How do I detect if the message is sent by a specific user id? - SO

'RawReactionActionEvent' object has no attribute 'author Issue with adding a cooldown on event

I'm trying to add a cooldown to a on_raw_reaction_add event in discord.py. I'm trying to do this by using cooldown mapping. The result should be to limit how many times this message
embed.description = f"It looks like you're joining us on a newly registered account. Verification requires accounts to be atleast a day old so please stick around and try again at {test_time.time().strftime(format)}."
is sent to a user if they don't meet the account age upon adding a reaction, which should be one reaction before the cooldown kicks in.
The error I get is 'RawReactionActionEvent' object has no attribute 'author not sure why this is happening.
Here is the full code I'm working with:
#commands.Cog.listener()
async def on_raw_reaction_add(self, payload): # Will be dispatched every time a user adds a reaction to a message the bot can se
general = self.bot.get_channel(701547632354525249)
introductions = self.bot.get_channel(705068046267580566)
botroom = self.bot.get_channel(706610280032894996)
if not payload.guild_id:
# In this case, the reaction was added in a DM channel with the bot
return
guild = self.bot.get_guild(payload.guild_id)
author = guild.get_member(payload.user_id)
bucket = self._cd.get_bucket(payload)
retry_after = bucket.update_rate_limit()
seconds = bucket.update_rate_limit()
seconds = round(seconds, 2)
hours, remainder = divmod(int(seconds), 3600)
minutes, seconds = divmod(remainder, 60)
if retry_after:
verification_error = f"You can do that again in **{minutes}m {seconds}s**."
embed = discord.Embed(title="You have already verified.", description=verification_error, colour=discord.Colour(0xff8100))
await message.channel.send(embed=embed)
pass
if payload.message_id != 743841858727444550:
return
else:
guild = self.bot.get_guild(payload.guild_id) # You need the guild to get the member who reacted
member = guild.get_member(payload.user_id) # Now you have the key part, the member who should receive the role
if payload.emoji.id != 743077610115956816:
reaction = payload.emoji.id
role = discord.utils.get(guild.roles, name="Members")
newbies = discord.utils.get(guild.roles, name="Newbies")
restricted_role = discord.utils.get(guild.roles, name="Restricted")
role = discord.Object(743840972068356116) # Pass the role's ID here
else:
return
if restricted_role in member.roles:
return
if member.created_at + dt.timedelta(days=30) <= dt.datetime.today():
await member.add_roles(role, reason='New member verified') # Finally add the role to the member
await member.add_roles(newbies, reason='New member verified') # Finally add the role to the member
welcome = f'Welcome {member.mention}! feel free to get started with adding some <#706648361196978177>'
intros = f'Hey {member.mention}! now that you\'re a member of our group, maybe you\'d like to tell us a bit about yourself. Tell us an interesting fact about yourself and so on... As always keep it sensible and fun.'
await general.send(welcome)
sent = await introductions.send(intros)
await asyncio.sleep(900)
await sent.delete()
else:
format = '%I:%M%p'
member1 = member.created_at.strftime("%I:%M%p")
dt3 = dt.datetime.strptime(member1, format)
test_time = dt3 + dt.timedelta(minutes = 1500)
embed = discord.Embed(colour=discord.Color(0x7289DA))
embed.title = f"Hey there {member.display_name}!"
embed.description = f"It looks like you're joining us on a newly registered account. Verification requires accounts to be atleast a day old so please stick around and try again at {test_time.time().strftime(format)}."
await member.send(embed=embed)
Help would be appreciated.
Under your #client.command statement just add
#commands.cooldown(1, 30, commands.BucketType.user)
This example will give a single user a cool down of 30 seconds for 1 use. You can configure BuckType to channel and server as well.

How to find Knowledge base ID (kbid) for QnAMaker?

I am trying to integrate QnAmaker knowledge base with Azure Bot Service.
I am unable to find knowledge base id on QnAMaker portal.
How to find the kbid in QnAPortal?
The Knowledge Base Id can be located in Settings under “Deployment details” in your knowledge base. It is the guid that is nestled between “knowledgebases” and “generateAnswer” in the POST (see image below).
Hope of help!
Hey you can also use python to get this by take a look at the following code.
That is if you wanted to write a program to dynamically get the kb ids.
import http.client, os, urllib.parse, json, time, sys
# Represents the various elements used to create HTTP request path for QnA Maker
operations.
# Replace this with a valid subscription key.
# User host = '<your-resource-name>.cognitiveservices.azure.com'
host = '<your-resource-name>.cognitiveservices.azure.com'
subscription_key = '<QnA-Key>'
get_kb_method = '/qnamaker/v4.0/knowledgebases/'
try:
headers = {
'Ocp-Apim-Subscription-Key': subscription_key,
'Content-Type': 'application/json'
}
conn = http.client.HTTPSConnection(host)
conn.request ("GET", get_kb_method, None, headers)
response = conn.getresponse()
data = response.read().decode("UTF-8")
result = None
if len(data) > 0:
result = json.loads(data)
print
#print(json.dumps(result, sort_keys=True, indent=2))
# Note status code 204 means success.
KB_id = result["knowledgebases"][0]["id"]
print(response.status)
print(KB_id)
except :
print ("Unexpected error:", sys.exc_info()[0])
print ("Unexpected error:", sys.exc_info()[1])

Password Changer using VAccess

Hey I am working on a password changer. User logs in ( successfully), loads a global var with user initials, then launch a password expired form. I try and use those initials on the password expired form to retrieve user info from DB.
vaUserLog.FieldValue("USERINIT") = UserInitials
vaUserLog.GetEqual
vaStat = vaUserLog.Status
vaStat keeps giving me an error of 4. I am using pervasive v9. Connection with VA looks like:
With vaUserLog
.RefreshLocations = True
.DdfPath = DataPath
.TableName = "USERLOG"
.Location = "USERLOG.MKD"
.Open
If .Status <> 0 Then
ErrMsg = "Error Opening File " + .TableName + " - Status " + str$(.Status) + vbCrLf + "Contact IT Department"
End If
End With
In DB table, USERINIT is Char, 3. UserInitials is a String.
Probably missing something small but can't think right now. Any help is appreciate. Lemme know if you require more info.
Cheers
Status 4 means that the record could not be found. In your case, it could be the case of the value being searched is wrong, there's a different padding (spaces versus binary zero), or that the UserInitials value just isn't in the data file.
You can use MKDE Tracing to see what's actually being passed to the PSQL engine. Once you've done that, make sure the value you're using works through the Function Executor where you can open the file and perform a GetEqual.
Here are my suggestions:
- Make sure you're pointing to the right data files.
- Make sure you're passing the right value into the GetEqual (by setting the FieldValue).

Django Session Persistent but Losing Data

I have been working for hours trying to understand the following problem: I have a user send an Ajax request to dynamically send a form and record that the number of forms to read on submission has increased. Toward this end I use request.session['editing_foo'] = { 'prefix_of_form_elements' : pkey } so that I can associate them with the database for saving and loading (-1 is for new forms that haven't been saved yet).
However, when I use the following code (see bottom) I get the following bizarre output:
1st Click:
{} foousername
next_key 1
1
{u'1-foo': -1}
2nd Click:
{} foousername
next_key 1
1
{u'1-foo': -1}
3rd Request:
{} foousername
next_key 1
1
{u'1-foo': -1}
What the heck is going on?
id_fetcher = re.compile(r'\d')
#login_required
def ajax_add_foo(request):
def id_from_prefix(key):
return int( id_fetcher.search(key).group(0) )
if 'editing_foos' not in request.session:
print "reinitializing"
request.session['editing_foos'] = {}
print request.session['editing_foos'], request.user
keys = request.session['editing_foos'].keys()
if len(keys) == 0:
next_key = 1
else:
print [ id_from_prefix(key) for key in keys ]
next_key = max([ id_from_prefix(key) for key in keys ]) + 1
print "next_key", next_key
fooform = FooForm(prefix=next_key)
print next_key
request.session['editing_foos'].update( {create_prefix(FooForm, next_key) : -1 } ) # This quote is new and has no pkey
print request.session['editing_foos']
return render_to_response( 'bar/foo_fragment.html',
{'fooform' : fooform, },
context_instance=RequestContext(request))
Thank you all very much!
Note: This is a followup to a previous question concerning the same source code.
I don't think I completely understand the question, but you may want to take a look at which session engine you're using
if you're using the cache session engine you need to make sure you have caching properly set up (for instance the dummy cache would just throw out your session data)
another possibility is that your session isn't being saved because you're not changing the session, you're changing a mutable object that is stored in the session. you can try forcing the session to save by adding this somewhere in your view:
request.session.modified = True

Resources