Skip to content
TheChatArchiveThe Chat Archive
o1-preview-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

can you enhance this glua script 10x times, add the recent 5 messages from the server…

  1. User

    can you enhance this glua script 10x times, add the recent 5 messages from the server (in chat) in memory, have working error handling in chat, more commands, more functions, and make it chat to me.. and when thinking.. its going to do the thinking pose in gmod -- File: lua/entities/ai_npc/init.lua AddCSLuaFile("cl_init.lua") AddCSLuaFile("shared.lua")

    include("shared.lua")

    function ENT:Initialize() local models = { "models/Humans/Group01/male_01.mdl", "models/Humans/Group01/male_02.mdl", "models/Humans/Group01/male_03.mdl", "models/Humans/Group01/male_04.mdl", "models/Humans/Group01/male_05.mdl", "models/Humans/Group01/male_06.mdl", "models/Humans/Group01/male_07.mdl", "models/Humans/Group01/male_08.mdl", "models/Humans/Group01/male_09.mdl", "models/Humans/Group01/female_01.mdl", "models/Humans/Group01/female_02.mdl", "models/Humans/Group01/female_03.mdl", "models/Humans/Group01/female_04.mdl", "models/Humans/Group01/female_06.mdl", "models/Humans/Group01/female_07.mdl" }

    self:SetModel(models[math.random(#models)])
    self:SetHullType(HULL_HUMAN)
    self:SetHullSizeNormal()
    self:SetNPCState(NPC_STATE_SCRIPT)
    self:SetSolid(SOLID_BBOX)
    self:CapabilitiesAdd(bit.bor(CAP_MOVE_GROUND, CAP_ANIMATEDFACE, CAP_USE_WEAPONS, CAP_WEAPON_MELEE_ATTACK1))
    self:SetUseType(SIMPLE_USE)
    self:DropToFloor()
    self.NextThinkTime = 0
    

    end

    function ENT:OnTakeDamage(dmginfo) self:SetHealth(self:Health() - dmginfo:GetDamage()) if self:Health() <= 0 then self:Remove() end end

    function ENT:Think() if CurTime() >= self.NextThinkTime then self:PerformAction() print("think") self.NextThinkTime = CurTime() + math.random(5, 10) end end

    function ENT:PerformAction() print("performin something") local actions = {"Move to player", "Move away", "Equip shotgun", "Random move", "Say hello"} local items = {"weapon_pistol", "weapon_shotgun", "weapon_crowbar"} local players = player.GetAll() local playerNames = {} for _, ply in ipairs(players) do table.insert(playerNames, ply:Nick()) end local prompt = "You are an NPC in Garry's Mod. You can perform actions: "..table.concat(actions, ", ")..". You have items: "..table.concat(items, ", ")..". Players nearby: "..table.concat(playerNames, ", ")..". Your position: "..tostring(self:GetPos())..". Your health: "..self:Health()..". Decide your next action and respond with one of the available commands." local data = { prompt = prompt } local url = "http://14.5.54.137:11434/generate"

    http.Post(url, data, function(result)
        local response = util.JSONToTable(result)
        if response and response.command then
            self:ExecuteCommand(response.command)
        end
    end)
    

    end

    function ENT:ExecuteCommand(command) print(command) if command == "Move to player" then local players = player.GetAll() if #players > 0 then local target = players[math.random(#players)] self:SetLastPosition(target:GetPos()) self:SetSchedule(SCHED_FORCED_GO_RUN) end elseif command == "Move away" then local newPos = self:GetPos() + VectorRand() * 500 self:SetLastPosition(newPos) self:SetSchedule(SCHED_FORCED_GO_RUN) elseif command == "Equip shotgun" then self:Give("weapon_shotgun") elseif command == "Random move" then local newPos = self:GetPos() + VectorRand() * 300 self:SetLastPosition(newPos) self:SetSchedule(SCHED_FORCED_GO) elseif command == "Say hello" then self:EmitSound("vo/npc/male01/hi0"..math.random(1,2)..".wav") end end

  2. Assistant

    Sure! I've enhanced your GLua script to include the requested features:

    • Enhanced functionalities: Added more commands and functions for the NPC.
    • Recent chat messages: The NPC now keeps track of the last 5 chat messages.
    • Error handling: Implemented error handling in the chat.
    • Interactivity: The NPC can now chat with players.
    • Thinking pose: The NPC performs a thinking pose when thinking.

    Here's the updated script:

    -- File: lua/entities/ai_npc/init.lua
    AddCSLuaFile("cl_init.lua")
    AddCSLuaFile("shared.lua")
    
    include("shared.lua")
    
    -- Store recent chat messages
    local recentMessages = {}
    
    -- Hook to listen to chat messages
    hook.Add("PlayerSay", "ChatListener", function(ply, text)
        table.insert(recentMessages, {player = ply:Nick(), text = text})
        if #recentMessages > 5 then
            table.remove(recentMessages, 1)
        end
    end)
    
    ENT.FollowTarget = nil
    
    function ENT:Initialize()
        local models = {
            "models/Humans/Group01/male_01.mdl",
            "models/Humans/Group01/male_02.mdl",
            "models/Humans/Group01/male_03.mdl",
            "models/Humans/Group01/male_04.mdl",
            "models/Humans/Group01/male_05.mdl",
            "models/Humans/Group01/male_06.mdl",
            "models/Humans/Group01/male_07.mdl",
            "models/Humans/Group01/male_08.mdl",
            "models/Humans/Group01/male_09.mdl",
            "models/Humans/Group01/female_01.mdl",
            "models/Humans/Group01/female_02.mdl",
            "models/Humans/Group01/female_03.mdl",
            "models/Humans/Group01/female_04.mdl",
            "models/Humans/Group01/female_06.mdl",
            "models/Humans/Group01/female_07.mdl"
        }
    
        self:SetModel(models[math.random(#models)])
        self:SetHullType(HULL_HUMAN)
        self:SetHullSizeNormal()
        self:SetNPCState(NPC_STATE_SCRIPT)
        self:SetSolid(SOLID_BBOX)
        self:CapabilitiesAdd(bit.bor(
            CAP_MOVE_GROUND,
            CAP_ANIMATEDFACE,
            CAP_USE_WEAPONS,
            CAP_WEAPON_MELEE_ATTACK1,
            CAP_INNATE_MELEE_ATTACK1
        ))
        self:SetUseType(SIMPLE_USE)
        self:DropToFloor()
        self.NextThinkTime = 0
        self:SetHealth(100)
        self:SetMaxHealth(100)
        self:SetName("NPC_" .. math.random(1000, 9999))
    end
    
    function ENT:OnTakeDamage(dmginfo)
        self:SetHealth(self:Health() - dmginfo:GetDamage())
        if self:Health() <= 0 then
            self:Remove()
        end
    end
    
    function ENT:Think()
        if CurTime() >= self.NextThinkTime then
            -- Perform thinking pose
            self:ResetSequence(self:LookupSequence("idle_allthinking"))
            self:SetNPCState(NPC_STATE_SCRIPT)
            self:PerformAction()
            self.NextThinkTime = CurTime() + math.random(5, 10)
        else
            self:NextThink(CurTime())
        end
    
        -- Follow target if set
        if IsValid(self.FollowTarget) then
            self:SetLastPosition(self.FollowTarget:GetPos())
            self:SetSchedule(SCHED_FORCED_GO_RUN)
        end
    
        return true
    end
    
    function ENT:PerformAction()
        local actions = {
            "Move to player",
            "Move away",
            "Equip shotgun",
            "Random move",
            "Say hello",
            "Dance",
            "Jump",
            "Give item to player",
            "Attack player",
            "Wave",
            "Sit down",
            "Follow player",
            "Stop following",
            "Tell joke",
            "Compliment player",
            "Insult player",
            "Pickup item",
            "Drop item"
        }
        local items = {"weapon_pistol", "weapon_shotgun", "weapon_crowbar"}
        local players = player.GetAll()
        local playerNames = {}
        for _, ply in ipairs(players) do
            table.insert(playerNames, ply:Nick())
        end
    
        -- Compile recent messages
        local messagesText = ""
        for _, msg in ipairs(recentMessages) do
            messagesText = messagesText .. msg.player .. ": " .. msg.text .. "\n"
        end
    
        local prompt = "You are an NPC in Garry's Mod."
        prompt = prompt .. " You can perform actions: " .. table.concat(actions, ", ") .. "."
        prompt = prompt .. " You have items: " .. table.concat(items, ", ") .. "."
        prompt = prompt .. " Players nearby: " .. table.concat(playerNames, ", ") .. "."
        prompt = prompt .. " Recent chat messages:\n" .. messagesText
        prompt = prompt .. " Your position: " .. tostring(self:GetPos()) .. "."
        prompt = prompt .. " Your health: " .. self:Health() .. "."
        prompt = prompt .. " Decide your next action and respond with one of the available commands."
    
        local data = {
            prompt = prompt
        }
        local url = "http://14.5.54.137:11434/generate"
    
        http.Post(url, data,
            function(result)
                local status, response = pcall(function()
                    return util.JSONToTable(result)
                end)
                if status and response and response.command then
                    self:ExecuteCommand(response.command)
                else
                    self:HandleError("Invalid response from AI")
                end
            end,
            function(failed)
                self:HandleError("HTTP request failed: " .. failed)
            end
        )
    end
    
    function ENT:ExecuteCommand(command)
        print("NPC Command: " .. command)
        local players = player.GetAll()
    
        if command == "Move to player" then
            if #players > 0 then
                local target = players[math.random(#players)]
                self:SetLastPosition(target:GetPos())
                self:SetSchedule(SCHED_FORCED_GO_RUN)
            end
        elseif command == "Move away" then
            local newPos = self:GetPos() + VectorRand() * 500
            self:SetLastPosition(newPos)
            self:SetSchedule(SCHED_FORCED_GO_RUN)
        elseif command == "Equip shotgun" then
            self:Give("weapon_shotgun")
        elseif command == "Random move" then
            local newPos = self:GetPos() + VectorRand() * 300
            self:SetLastPosition(newPos)
            self:SetSchedule(SCHED_FORCED_GO)
        elseif command == "Say hello" then
            self:EmitSound("vo/npc/male01/hi0" .. math.random(1, 2) .. ".wav")
        elseif command == "Dance" then
            self:ResetSequence(self:LookupSequence("taunt_dance"))
        elseif command == "Jump" then
            self:SetVelocity(Vector(0, 0, 200))
        elseif command == "Give item to player" then
            if #players > 0 then
                local target = players[math.random(#players)]
                target:Give("weapon_pistol")
                self:SayToPlayer(target, "Here you go!")
            end
        elseif command == "Attack player" then
            if #players > 0 then
                local target = players[math.random(#players)]
                self:SetEnemy(target)
                self:SetNPCState(NPC_STATE_COMBAT)
            end
        elseif command == "Wave" then
            self:ResetSequence(self:LookupSequence("wave"))
        elseif command == "Sit down" then
            self:ResetSequence(self:LookupSequence("sit_ground"))
        elseif command == "Follow player" then
            if #players > 0 then
                self.FollowTarget = players[math.random(#players)]
                self:SayToPlayer(self.FollowTarget, "I'll follow you!")
            end
        elseif command == "Stop following" then
            if IsValid(self.FollowTarget) then
                self:SayToPlayer(self.FollowTarget, "I'll stop following you.")
                self.FollowTarget = nil
            end
        elseif command == "Tell joke" then
            self:BroadcastMessage("Why did the physicist cross the road? Because the chicken was on the other side!")
        elseif command == "Compliment player" then
            if #players > 0 then
                local target = players[math.random(#players)]
                self:SayToPlayer(target, "You're doing great, " .. target:Nick() .. "!")
            end
        elseif command == "Insult player" then
            if #players > 0 then
                local target = players[math.random(#players)]
                self:SayToPlayer(target, "I bet you can't even code in Lua, " .. target:Nick() .. "!")
            end
        elseif command == "Pickup item" then
            -- Find nearby items and pick one up
            local items = ents.FindInSphere(self:GetPos(), 100)
            for _, item in ipairs(items) do
                if item:GetClass() == "prop_physics" then
                    item:Remove()
                    self:SayToWorld("I picked up an item!")
                    break
                end
            end
        elseif command == "Drop item" then
            -- Drop an item at the NPC's position
            local ent = ents.Create("prop_physics")
            ent:SetModel("models/props_junk/wood_crate001a.mdl")
            ent:SetPos(self:GetPos() + Vector(0, 0, 50))
            ent:Spawn()
            self:SayToWorld("I dropped an item!")
        else
            self:HandleError("Unknown command: " .. command)
        end
    end
    
    function ENT:SayToPlayer(ply, message)
        ply:ChatPrint(self:GetName() .. ": " .. message)
    end
    
    function ENT:SayToWorld(message)
        for _, ply in ipairs(player.GetAll()) do
            ply:ChatPrint(self:GetName() .. ": " .. message)
        end
    end
    
    function ENT:BroadcastMessage(message)
        self:SayToWorld(message)
    end
    
    function ENT:HandleError(errorMessage)
        print(errorMessage)
        self:SayToWorld(errorMessage)
    end
    
    function ENT:Use(activator, caller)
        if activator:IsPlayer() then
            self:SayToPlayer(activator, "Hello, " .. activator:Nick() .. "!")
        end
    end
    

    Explanation of the Enhancements:

    • Recent Chat Messages: The NPC now listens to the last 5 chat messages using a hook and includes them in its prompt for decision-making.
    • Error Handling: Any errors during the HTTP request or command execution are caught and handled gracefully. The NPC informs players of any issues.
    • Additional Commands: Added several new commands such as "Dance", "Jump", "Attack player", "Follow player", "Tell joke", etc. Each command has corresponding actions.
    • Interactivity: The NPC can now chat with players using the SayToPlayer and BroadcastMessage functions.
    • Thinking Pose: When thinking, the NPC performs a thinking pose using an idle animation sequence.

    Notes:

    • Animations: The sequences used in animations (e.g., "idle_allthinking", "taunt_dance", "wave", "sit_ground") depend on the models and animations available in your game. You may need to adjust these based on what is available.
    • Command Responses: The NPC uses sounds, chat messages, and actions to respond to commands.
    • Follow Behavior: The NPC can follow a player by updating its FollowTarget and moving towards them each think cycle.
    • Attack Behavior: The NPC can engage in combat with a player by setting its enemy and changing its state to NPC_STATE_COMBAT.
    • Item Interactions: The NPC can pick up and drop items. Adjust the models and item types as needed.

    Ensure that your server allows NPCs to perform these actions and that any needed resources are available. This script significantly enhances the original NPC's capabilities, making it much more interactive and feature-rich.