Get a user id from a mention - discord.py

I search how I can get a user id from a mention (from other user, not me). I tried to do this with split():
bet1=message.content.split(" ")[1]
bet1=message.content.split("<")[1]
bet1=message.content.split("#")[1]
but that is not working because he reads after the from one splited symbol to the next same
bet1=message.content.split(">")[1]

You should use message.mentions.
if message.mentions: #check if message has any mentions
if isinstance(message.mentions[0], discord.Member) or isinstance(message.mentions[0], discord.User): #checking if the first mention is of a User or a Member (User in server)
await message.channel.send(message.mentions[0].id)

Related

Cant get user name discord.py

I am making a bot for my favorite twitch streamer and medium length story short, I need a profile function for the bot. It works when you don't # someone in the second argument, but I want people to be able to see another users profile.
async def profile(ctx, user=None):
if user:
user = discord.User.display_name
else:
user = ctx.message.author.name
with open('users.json', 'r') as f:
file = json.load(f)
await ctx.send(f'PP: ``{file[user]}``')
users.json looks like this:
Your code at its current stage is quite confusing. Let me explain:
You have no method of properly accessing your user, instead calling an empty object.
You're using two separate ways to get the name, via name and display_name, which are two separate names. Adding to this, this method does not take into account that two users may have the same name.
You can define discord.Member within the command itself. If there is no user mentioned, this will default to the command author, ctx.author (which is the same as ctx.message.author).
In the code below, you will notice two ways of I have defined the variable user_info. If you're going to access the numbers based on a discord user's name, I would highly recommend replacing the name with the user id so you can access other discord user information via get_member or similar. Otherwise, feel free to continue using user.name.
Do view the revised code below.
async def profile(ctx, user:discord.Member=None):
if not user:
user = ctx.author
# either continue to save with the name..
user_info = user.name # or user.display_name but don't use both!
# ..or save with their user id
user_info = str(user.id)
with open('users.json', 'r') as f:
file = json.load(f)
await ctx.send(f'PP: ``{file[user_info]}``')

Discord.py Getting a number of messages deleted from audit log

I'm making a logging system with discord.py. For now, I'm trying to get the number of messages were deleted from a single audit log entry (since sometimes the audit logs updates an entry instead of creating a new one), so I tried with "entry.action.count". Here's my code
#client.command()
#commands.has_permissions(administrator=True)
async def deletecount(ctx):
async for entry in ctx.guild.audit_logs(limit=1, action=discord.AuditLogAction.message_delete):
print(entry.action.count)
But instead of printing the number of messages deleted, it just prints
<built-in method count of _EnumValue_AuditLogAction object at 0x000001FF9769C640>
From this screenshot, in this case the latest entry has 5 deleted messages. I'm trying to print out that "5". So how do I get the number of message deleted from the latest audit log entry? The documentation doesn't have further information on how to use the extra attribute for entry.action.
I should also add that I have asked someone about this, they suggested to try print(entry.action.count()), but I got
TypeError: tuple.count() takes exactly one argument (0 given)
What is the argument that should be given there? Thanks in advance.
It is possible, use the extra attribute and it will return a dict with the data you want (the docs don't give you a lot of information about it because the return value differs from the type of action):
async for entry in ctx.guild.audit_logs(limit=1, action=discord.AuditLogAction.message_bulk_delete):
count = entry.extra['count']
The return value of AuditLogEntry.extra varies depending on the type of event, the example above will only work with message_bulk_delete
PS: You were using the wrong action in the iterator, it should be AuditLogAction.message_bulk_delete not AuditLogAction.message_delete
References:
AuditLogEntry.extra

Powershell and IBM/Lotus Domino

I have written 9 routines in the last few weeks in Powershell for Domino, they all appear to do what I need except 1!
This is the RegisterNewUser method, which does everything except the Email address. If I setup a user via Domino Administrator, I get everything including the email address ie internal address that is 'bob patz/smallhome'.
If I use my code this uses the registration process but all I end up with is the domain part of the internal email address '#smallhome'.
Does anyone know how to correct this? I don't think powershell uses the #formula language in any form, so I assume i somehow need to find the right column in a document or database and append the fullname in there somehow.
Is there anyone out there who can help in anyway?
regards
Mark
<#TOP TIP: THIS MUST RUN UNDER POWERSHELL (X86), ELSE IT WILL NOT WORK!!
This Powershell Function was created in March 2020 by (myself) Mark Baker as 'a' just to see if I can de-mystify
some of the Domino Database stucture, after running short bits of code and using Get-Member on some parts
of it and looking at online code snippets and reading some of the online info from IBM I have come up with
the function below to Create a New Lotus Notes User.
#
Original Code: 31/03/2020 by MBaker
A lot of work testing and diagnosing the different settings and values EVENTUALLY lead me to getting this working,
as at 08/04/2020 I just need to work out the settings for setting the correct email address per person.
#
This is how to use this function:
New-DominoUserRegistration "hazell" "C:\Program Files\IBM\Lotus\Notes\Data\ids\people\dhazell.id" "CN=Dom-01/O=Smallhome"
"Daniel" "" "swindon" "Work" "comment" "mail\dhazell" " " "password" 176
"dhazell"
Main use of this function is to connect to an IBM Domino Server and Create a New lotus notes user.
>
Function New-DominoUserRegistration {
[cmdletbinding()]
param (
[parameter(Position=0,Mandatory=$true,ValueFromPipeline=$True)][string]$lastname,
[parameter(Position=1,Mandatory=$true,ValueFromPipeline=$True)][string]$Useridfile,
[parameter(Position=2,Mandatory=$true,ValueFromPipeline=$True)][string]$mailserver,
[parameter(Position=3,Mandatory=$true,ValueFromPipeline=$True)][string]$firstname,
[parameter(Position=4,Mandatory=$false,ValueFromPipeline=$True)][string]$middle,
[parameter(Position=5,Mandatory=$true,ValueFromPipeline=$True)][string]$certpw,
[parameter(Position=6,Mandatory=$true,ValueFromPipeline=$True)][string]$location,
[parameter(Position=7,Mandatory=$true,ValueFromPipeline=$True)][string]$comment,
[parameter(Position=8,Mandatory=$true,ValueFromPipeline=$True)][string]$maildbpath,
[parameter(Position=9,Mandatory=$true,ValueFromPipeline=$True)][string]$fwddomain,
[parameter(Position=10,Mandatory=$true,ValueFromPipeline=$True)][string]$userpw,
[parameter(Position=11,Mandatory=$true,ValueFromPipeline=$True)][int]$usertype,
[parameter(Position=12,Mandatory=$true,ValueFromPipeline=$True)][string]$ShortName
)
cls
# Create Lotus Notes Object
$DomSession = New-Object -ComObject Lotus.NotesSession
# Initialize Lotus Notes Object
# "It'll use your open notes session and authentication Details"
$DomSession.Initialize()
# Use Method from Objects returned in variable $domsession one of which is CreateAdministrationProcess which
# takes a Server as input
$adminProcess = $Domsession.CreateRegistration()
$expiration = (Get-Date).adddays(1095)
$adminprocess.certifieridfile="C:\Program Files (x86)\IBM\Lotus\Notes\Data\ids\cert.id"
$adminprocess.Expiration =$expiration
#$adminprocess.RegistrationLog ="C:\program files (x86)\IBM\lotus\notes\data\reglog.nsf"
#[int]$adminProcess.MinPasswordLength=5
$adminprocess.RegistrationServer="Dom-01/smallhome"
$adminprocess.UpdateAddressBook=$true
$adminProcess.GroupList="Test4"
#$adminProcess.CreateMailDb=$true
#[int]$adminProcess.MailQuotaSizeLimit="100"
#[int]$adminProcess.MailQuotaWarningThreshold="90"
$adminProcess.PolicyName="/Registration_Settings"
$adminProcess.ShortName=$ShortName
[int]$adminProcess.MailOwnerAccess=2
$adminProcess.MailACLManager="LocalDomainAdmins"
$adminProcess.MailInternetAddress="$ShortName"+"#smallhome.local"
$adminProcess.MailTemplateName="Mail85.ntf"
$Notesid=$adminprocess.RegisterNewUser($lastname,$Useridfile,$mailserver,$firstname,$middle,$certpw,$location,$comment,$maildbpath,$fwddomain,$userpw,$usertype)
}
New-DominoUserRegistration "archer" "C:\Program Files (x86)\IBM\Lotus\Notes\Data\ids\people\barcher.id" "CN=Dom-01/O=Smallhome" "basil" "" "swindon" "Work" "comment" "mail\barcher" " " "password" 176 "barcher"
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/2Wamq.png
I now have an answer for this, this came from someone else on another board: the line [parameter(Position=9,Mandatory=$true,ValueFromPipeline=$True)][string]$fwddomain,
Needed to have [AllowEmptyString()] inserted before [string]$fwddomain, and the input field was " " and needed to be "". It appears the $fwddomain has an impact on the internal email address name ie: 'bob patz/smallhome'.
I have tested this and it shows up in the people view and also I can now send emails to other users and ones self!
Problem solved.
Regards
Mark

How to get UserName from Computer?

I'm searching to get back the String on the red block.
I already tried the following code:
Environment.UserName
My.User.Name
SystemInformation.UserName
System.Security.Principal.WindowsIdentity.GetCurrent().Name
Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
Environment.GetFolderPath(Environment.GetEnvironmentVariable("%USERNAME%"))
But this code don't work, because the computer of my company uses a domain, and the String that I need is different as the user.
The user is composed only by the name, and the string is composed by the name and the first name of the employees.
I finally found what I need here
We have to import that :
“System.DirectoryServices.AccountManagement”
“System.DirectoryServices”
And write this two lines to get back the red block.
Dim currentADUser As System.DirectoryServices.AccountManagement.UserPrincipal
currentADUser = System.DirectoryServices.AccountManagement.UserPrincipal.Current
You can try using either
HttpContext.Current.Server.MachineName
or
System.Environment.MachineName;

Adding members to security group: SetInfo returns error 80070005

Background
I working on (modifying) a vbscript intended to create an AD shadow group formed by all users of several OU's.
The script logs into a remote AD, using alternate credentials.Note: The user I log in as, have full AD read access, but only inherited write access to the OU containing the group I'm adding members to.
Problematic code
The script is easily able to log in, scan for users on the OU's, open the shadow group and list it's current members, perform compares and locate the users to add and remove....but...
the actual adding (and removing) of members to the named security group fails, Error: 80070005 Srce: Active Directory Desc: Access is denied., when I apply .SetInfo.
I'm using this code to read and write:
aMembers = oGroup.GetEx("member") ' This gets populated as it should.
oGroup.PutEx ADS_PROPERTY_APPEND, "member", Array("CN=Doe\, John [LOCATION/COUNTRY],OU=foo,OU=bar,OU=Country,DC=domain,DC=org")
oGroup.SetInfo ' This fails
Just in case this is related to how I log into the AD, here's the code:
' Open an ADO connection using full credentials
Set oConnection = CreateObject("ADODB.Connection")
oConnection.Provider = "ADsDSOObject"
oConnection.Properties("User ID") = sLDAP_USER ' "domain\user"
oConnection.Properties("Password") = sLDAP_PASS ' "pass!word"
oConnection.Properties("Encrypt Password") = True
oConnection.Properties("ADSI Flag") = ADS_SECURE_AUTHENTICATION Or ADS_SERVER_BIND
oConnection.Open "Active Directory Provider"
Verifying my login users rights
I've seen lots of similar posts with this sort of error, and have only seen answers stating that this is a permission problem - however never seen a description of what permission was missing/wrong. The Access is denied error really made me doubt that the login I used had the right permissions, so I attempted to add members to the group by using JXplore. It works, but only if I enable the option to ignore schema checking (Based on online advice, when using JXplore with AD instead of pure LDAP).
Edit: Without ignoring the schema checking, the following properties are also requested to be populated: instanceType, nTSecurityDescriptor and objectCatagory, but I notice they are blank on existing users.
Questions
Did I fall into an obvious pitfall?
Do I also somehow need to ignore the schema in my script? If so, how to do that?

Resources